如果在一的@OneToMany有@manyToOne则是双向一对多关联,如果在多的那面没有@manyToOne关联则是单向一对多关联
class和student是一对多的关系
表结构
student
class
Class
package auth.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="class")
public class Room {
private int id;
private String name;
private List<Student> students=new ArrayList<Student>();
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = CascadeType.ALL
,fetch=FetchType.EAGER
)
@JoinColumn(name="room_id")
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student
package auth.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
private int id;
public int room_id;
private String name;
@GeneratedValue(strategy= GenerationType.AUTO)
@Id
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="room_id")
public int getRoom_id() {
return room_id;
}
public void setRoom_id(int room_id) {
this.room_id= room_id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Dao
package auth.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import auth.model.MyClass;
public interface ClassDao extends JpaRepository<MyClass, Integer>{
}
测试
@Autowired
private ClassDao dao;
public void add(){
Room room=new Room();
room.setName("5班");
Student s=new Student();
s.setName("小王");
room.getStudents().add(s);
dao.save(room);
Student s1=new Student();
s.setName("小李");
room.getStudents().add(s1);
dao.save(room);
}
public void query(){
Student s=stuDao.findOne(2);
System.out.println(JSONObject.toJSONString(s));
}
public void query1(){
Rooms=dao.findOne(2);
System.out.println(JSONObject.toJSONString(s));
}
过程
insert
into
class
(name)
values
(?)
2017-06-04 23:56:04,251 DEBUG [org.hibernate.id.IdentifierGeneratorHelper:94] - Natively generated identity: 3
2017-06-04 23:56:04,272 DEBUG [org.hibernate.engine.spi.ActionQueue:196] - Executing identity-insert immediately
2017-06-04 23:56:04,273 DEBUG [org.hibernate.SQL:109] -
insert
into
student
(room_id, name)
values
(?, ?)
第一个查询只能查出Student的数据,第二个可以把Class和Student的数据查出来(要设置fetch=FetchType.EAGER)