V
V
Vitaly2014-01-06 20:13:17
Java
Vitaly, 2014-01-06 20:13:17

Hibernate many-to-one and one-to-many?

There are two entities, the main one (UserEntity) and the plugged one (TodoEntity)
In theory, you need a request userEntity.getTodo(); Get a list of all entries in the Todo table that are associated with a specific user. Associated as follows - the parent_id field in the todo table must be associated with the id field in the users table, where id is the primary key. Those. one user - a lot of things tied to it.
Tried to implement one-to-many and many-to-one, got a mapping error.

Could not determine type for: java.util.Set, at table: test_users, for columns: [org.hibernate.mapping.Column(todoEntity)]
, Googling, I found that there could be a great many problems, but none of the solutions already found solved the problem. Did on this guide (the first part) Question two guide .
First, is it worth using this kind of relationship when you can just add a function to UserDAO to get all records from the todo table where parent_id: id? Or is it bad practice, if so - why?
Second. If it is still worth using a connection, how to implement it? With a nose in a guide or a short code, I tried many different guides, none of them worked.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
Haderach, 2014-01-06
@Haderach

For example, you can try this:
Suppose you have a Task class, something similar to:

@Entity 
@Table (name = "todo")
public class Task {
.....
@ManyToOne
@JoinColumn(name = "userId")
private User responsibleUser;
.....
}

And the user class, like this:
@Entity 
@Table (name = "users")
public class User {
.....
@Id
@Column (name = "userId")
private Integer userId;

@OneToMany (mappedBy = "responsibleUser")
private Set<Task> tasks = new HashMap<Task>();
.....
}

Well, then what you need for implementation.
PS I wrote the code from memory, so don't get angry for mistakes, I think the main idea is clear;)

F
FanKiLL, 2014-01-06
@FanKiLL

@Entity
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @Column(unique = true, nullable = false)
  private String userName
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
  private Set<Todo> todos = new HashSet<Todo>();
}

@Entity
public class Todo {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @ManyToOne()
  @JoinColumn(name = "user_id")
  private User user;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question