java 如何使用带有 JBOSS 工具的休眠在数据库中添加新记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11392404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:54:34  来源:igfitidea点击:

How can I add new record in database using hibernate with JBOSS Tool?

javamysqlhibernatepojojboss-tools

提问by Jyun Wei Chen

I am using Eclipse and JBOSS Tool to generate hibernate class from MySQL. The salary table have composite key, one is FK(userId), one is AUTO_INCREMENT. So JBOSS Tool generated Salary and User class, it also generated SalaryId class. I have added cascade in getSalaries method of User class, but when I tried to save the new user, I always get the exception: org.hibernate.exception.ConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

我正在使用 Eclipse 和 JBOSS 工具从 MySQL 生成休眠类。工资表有复合键,一个是FK(userId),一个是AUTO_INCREMENT。所以JBOSS Tool 生成了Salary 和User 类,它也生成了SalaryId 类。我在 User 类的 getSalaries 方法中添加了级联,但是当我尝试保存新用户时,总是出现异常: org.hibernate.exception.ConstraintViolationException:无法添加或更新子行:外键约束失败

Does anyone have any idea to help me solve this problem? Thanks all~

有没有人有任何想法可以帮助我解决这个问题?谢谢大家~

Below are my table structure:

下面是我的表结构:

CREATE TABLE IF NOT EXISTS `salary` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `userId` int(11) NOT NULL,
 `amount` int(11) NOT NULL,
 `comingDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`,`userId`),
 KEY `userId` (`userId`)
)

Below are my generated class: [User class]

下面是我生成的类:[用户类]

@Entity
@Table(name = "user", catalog = "lab")
public class User implements java.io.Serializable {

    private Integer id;
    private String name;
    private String password;
    private String email;
    private Set<Salary> salaries = new HashSet<Salary>(0);

    public User() {
    }

    public User(String name, String password, String email, Set<Salary> salaries) {
        this.name = name;
        this.password = password;
        this.email = email;
        this.salaries = salaries;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name", nullable = false, length = 100)
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "password", nullable = false, length = 100)
    public String getPassword() {
        return this.password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    @Column(name = "email", nullable = false, length = 50)
    public String getEmail() {
        return this.email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
    public Set<Salary> getSalaries() {
        return this.salaries;
    }
    public void setSalaries(Set<Salary> salaries) {
        this.salaries = salaries;
    }
}

[Salary class]

【薪资等级】

@Entity
@Table(name = "salary", catalog = "lab")
public class Salary implements java.io.Serializable {

    private SalaryId id;
    private User user;
    private int amount;
    private Date comingDate;

    public Salary() {
    }

public Salary(SalaryId id, User user, int amount) {
        this.id = id;
        this.user = user;
        this.amount = amount;
    }

    public Salary(SalaryId id, User user, int amount, Date comingDate) {
        this.id = id;
        this.user = user;
        this.amount = amount;
        this.comingDate = comingDate;
    }

    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "id", column = @Column(name = "id", nullable = false)),
            @AttributeOverride(name = "userId", column = @Column(name = "userId", nullable = false)) })
    public SalaryId getId() {
        return this.id;
    }

    public void setId(SalaryId id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId", nullable = false, insertable = false, updatable = false)
    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Column(name = "amount", nullable = false)
    public int getAmount() {
        return this.amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "comingDate", nullable = false, length = 19)
    public Date getComingDate() {
        return this.comingDate;
    }

    public void setComingDate(Date comingDate) {
        this.comingDate = comingDate;
    }
}

Below is auto generated by JBOSS Tool:

以下是 JBOSS 工具自动生成的:

[SalaryId class]

[SalaryId 类]

@Embeddable
public class SalaryId implements java.io.Serializable {

    private int id;
    private int userId;

    public SalaryId() {
    }

    public SalaryId(int id, int userId) {
        this.id = id;
        this.userId = userId;
    }

    @Column(name = "id", nullable = false)
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(name = "userId", nullable = false)
    public int getUserId() {
        return this.userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public boolean equals(Object other) {
        if ((this == other))
            return true;
        if ((other == null))
            return false;
        if (!(other instanceof SalaryId))
            return false;
        SalaryId castOther = (SalaryId) other;

        return (this.getId() == castOther.getId())
                && (this.getUserId() == castOther.getUserId());
    }

    public int hashCode() {
        int result = 17;

        result = 37 * result + this.getId();
        result = 37 * result + this.getUserId();
        return result;
    }
}

[Main class]

【主课】

transaction = session.beginTransaction();
SalaryId salaryId = new SalaryId();
Set<Salary> salaries = new HashSet<Salary>();

User user = new User();
user.setName("JW");
user.setPassword("123456");
user.setEmail("[email protected]");

salaries.add(new Salary(salaryId, user, 10000));
user.setSalaries(salaries);

session.save(user);

transaction.commit();

回答by zato

Try to do like this:

尝试这样做:

transaction = session.beginTransaction();
SalaryId salaryId = new SalaryId();
Set<Salary> salaries = new HashSet<Salary>();

User user = new User();
user.setName("JW");
user.setPassword("123456");
user.setEmail("[email protected]");

session.save(user);

salaries.add(new Salary(salaryId, user, 10000));
//user.setSalaries(salaries);

transaction.commit();