Note that there are some explanatory texts on larger screens.

plurals
  1. POHibernate One-To-One relationship
    text
    copied!<p>I see many turoials and articles about subject, but i can't understand one thing. For a example: i have "User" table with fields "id", "name" and i have "UserBanned" table with fields "userid" and "reason". UserBanned.userid - it is link (foreign key) on field User.id.</p> <p>So, models in hiberante looks like:</p> <pre><code>@Entity @Table(name = "user") @DynamicInsert public class User{ @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "user_id_generator") @SequenceGenerator(name = "user_id_generator", sequenceName = "user_id_seq") protected Integer id; @Column protected Integer name; @OneToOne (mappedBy = "user", cascade = CascadeType.ALL) protected UserBanned userBanned; </code></pre> <p>And UserBanned model:</p> <pre><code>@Entity @Table(name = "userbanned") @DynamicInsert public class UserBanned{ @Id @Column(name="userid", unique=true, nullable=false) @GeneratedValue(generator="gen") @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user")) protected Integer userid; @Column protected String reason; @OneToOne @PrimaryKeyJoinColumn protected User user; </code></pre> <p>And it works. I can create new user and banned user with this code:</p> <pre><code> User user = new User(); user.setName(name); UserBanned userBanned = new UserBanned (); userBanned.setReason(reason); user.setUserBanned(userBanned ); userBanned.setUser(user); clientService.store(user); </code></pre> <p>But, when i try to do gson.toJson(client) i got stackoverflow error - because Gson can't handle circular references in the serialized data. But my mind cant understand why i have to set User in UserBanned?! Why i can not just have model User?</p> <p>My question: how i can organize such relationship (One-To-One with foreign key) like User (there are not only UserBanned, but and UserVIP and etc entities) in hibernate?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload