@OneToOne映射与Hibernate共享主键用户 - 帐户

时间:2016-08-02 23:29:30

标签: java jpa orm

我已经尝试让this example为我的情况工作。 Primus是User,Secundus是Account。用户应与Account共享主键。一切正常,直到我尝试级联坚持。:

User user = new User();
user.setName("Andy");
this.uDao.create(user);

没关系,但是......

User user = new User();
user.setName("Andy");
Account account = new Account();
account.setUsername("xyz");
user.setAccount(account);
this.uDao.create(user);

给出错误:

01:14:35,844 INFO  [stdout] (ServerService Thread Pool -- 80) Hibernate: insert into user (name) values (?)

01:14:35,860 INFO  [stdout] (ServerService Thread Pool -- 80) Hibernate: insert into account (username, user_id) values (?, ?)

01:14:35,861 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (ServerService Thread Pool -- 80) SQL Error: 1452, SQLState: 23000
01:14:35,861 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (ServerService Thread Pool -- 80) Cannot add or update a child row: a foreign key constraint fails (`shitstorm`.`account`, CONSTRAINT `fk_account_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

我该怎么办?我的错是什么?我在硕士论文中,在我的数据库中有一些1:1的关系,需要处理这个问题。让Cascading.persist工作对我来说很重要。我尝试了很多教程并阅读了很多解释,但我无法处理这种情况。我在链接中发布的教程是我的最后一次尝试。该应用程序正在Wildfly 8.2.1上运行。非常感谢!

这是SQL:

CREATE TABLE IF NOT EXISTS `shitstorm`.`user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (`id`))

-- -----------------------------------------------------
-- Table `shitstorm`.`account`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `shitstorm`.`account` (
  `user_id` INT(11) NOT NULL,
  `username` VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (`user_id`),
  INDEX `fk_account_user_idx` (`user_id` ASC),
  CONSTRAINT `fk_account_user`
    FOREIGN KEY (`user_id`)
    REFERENCES `shitstorm`.`user` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

以下是我的实体:

@Entity
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(unique=true, nullable=false)
    private int id;

    @Column(length=45)
    private String name;

    //bi-directional one-to-one association to Account
    @OneToOne(cascade=CascadeType.PERSIST, mappedBy="user")
    private Account account;

    public User() {
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
        if(this.account != null){
            this.account.setUserId(id);
        }
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Account getAccount() {
        return this.account;
    }

    public void setAccount(Account account) {
        this.account = account;
        if(account != null){
            account.setUser(this);
        }
    }

}

   @Entity
    @Table(name="account")
    @NamedQuery(name="Account.findAll", query="SELECT a FROM Account a")
    public class Account implements Serializable {
        private static final long serialVersionUID = 1L;

        @Id
        @Column(name="user_id", unique=true, nullable=false)
        private int userId;

        @Column(length=45)
        private String username;

        //bi-directional one-to-one association to User
        @OneToOne
        @PrimaryKeyJoinColumn(name="user_id")
//@JoinColumn(name="user_id", nullable=false, insertable=false, updatable=false) -- was generated by JPA TOOLS
        private User user;



        public Account() {
        }

        public int getUserId() {
            return this.userId;
        }

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

        public String getUsername() {
            return this.username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public User getUser() {
            return this.user;
        }

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

    }

1 个答案:

答案 0 :(得分:2)

您可以在JPA 2+中更简单地实现此目的,如下所示:

public class User{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(unique=true, nullable=false)
    private int id;

    @OneToOne(cascade=CascadeType.PERSIST, mappedBy = "user")
    private Account account;
}

public class Account{

    @Id
    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
}

请参阅:

https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships