@OneToOne Mapping with Hibernate shared primary ke

2020-04-26 07:07发布

问题:

i have tried out to bring this example to work for my Situation. Primus is User, Secundus is Account. User should share the primary key with Account. Everything works fine till i try to cascade a persist.:

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

is okay and works, but...

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

gives the error:

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)

What can i do? What is my mistake? I'm in my master thesis and have some 1:1 relationships in my database and need to handle this. It's important for me to bring the Cascading.persist to work. I tried out so many tutorials and read so many explanations but i can't handle this situation. The tutorial i have posted in the link was my last attempt. The aaplication is running on Wildfly 8.2.1 Thank's a lot!

Here is the 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)

Here are my Entities:

@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);
        }
    }

}

and

   @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:

You can achieve this more simply in JPA 2+ as follows:

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;
}

See:

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



标签: java jpa orm