Good day! Help me find a bug in the implementation of the OneToOne Hibernate connection.

There are 2 tables in PostgreSql

CREATE TABLE user_profile ( id serial NOT NULL, first_name character varying(255), last_name character varying(255), middle_name character varying(255), created timestamp without time zone NOT NULL DEFAULT now(), birthday timestamp without time zone NOT NULL, CONSTRAINT user_profile_pkey PRIMARY KEY (id), ); CREATE TABLE user_account ( id serial NOT NULL, email character varying(200) NOT NULL, password character varying(255) NOT NULL, login character varying(255) NOT NULL, coins integer NOT NULL DEFAULT 0, CONSTRAINT user_account_pkey PRIMARY KEY (id), CONSTRAINT user_account_email_key UNIQUE (email), CONSTRAINT user_account_id_fkey FOREIGN KEY (id) REFERENCES user_profile (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ); 

So I do mappings (heters and setters removed to save space):

  @Entity public class UserProfile extends AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String firstName; @Column private String lastName; @Column private String middleName; @Column private Date created; @Column private Date birthday; } @Entity public class UserAccount extends AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String login; @Column private String password; @Column(updatable = true) private String email; @Column private Long coins; @MapsId @OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinColumn(updatable = false, name = "id") private UserProfile userProfile; } 

Testing:

  @Test public void firstTest(){ final UserAccount userAccount = createRandomUserAccount(); final UserProfile userProfile = createRandomUserProfile(); userService.createNewUser(userAccount, userProfile); } @Override @Transactional public void createNewUser(UserAccount userAccount, UserProfile userProfile){ userAccount.setUserProfile(userProfile); accountDao.insertEntity(userAccount); } @Override public Entity insertEntity(final Entity entity){ entityManager.persist(entity); return entity; } 

After execution, only UserProfile is added to the database, UserAccount remains empty, there are no errors.

    1 answer 1

    1 - check that in the createRandomUserProfile(); method createRandomUserProfile(); no persistʻa to the base. There is a suspicion that you have a conflict in transactional managers - for business logic one, for tests - another (if you, of course, specify Spring Runner).

    2 - you can check the workaround - obviously add the @Rollback annotation. Although with the correct configuration, it should be so for tests.

    • Thanks for the answer, but I already figured out the error, forgot to update the question. The problem was that the record was removed from the Spring configuration file - <tx: annotation-driven />. After adding it all worked again. - Sined