表结构
Room类
package auth.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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="room")
public class Room {
private int id;
private String name;
private Set<Student> students=new HashSet<Student>();
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
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(mappedBy="room",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
private int id;
private String name;
private int room_id;
private Room room;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
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;
}
@Column(name="room_id")
public int getRoom_id() {
return room_id;
}
public void setRoom_id(int room_id) {
this.room_id = room_id;
}
@ManyToOne
@JoinColumn(name="room_id",insertable=false, updatable=false)
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
}
测试类:
package auth.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import auth.dao.RoomDao;
import auth.dao.StudentDao;
import auth.model.Room;
import auth.model.Student;
@Service
public class RoomController {
@Autowired
private RoomDao dao;
@Autowired
private StudentDao dao1;
public void add(){
Room room=new Room();
room.setName("教室3");
dao.save(room);
Student s=new Student();
s.setName("小王1");
s.setRoom_id(room.getId());//维护方是多的一方,所以不会主动关联一方的ID
dao1.save(s);
}
public void query1(){
Student student=dao1.findOne(5);
String xx=JSONObject.toJSONString(student);
System.out.println(xx);
}
public void query2(){
Room room=dao.findOne(3);
String xx=JSONObject.toJSONString(room);
System.out.println(xx);
}
}