以学生和电脑为例(Student-Computer)
建表sql语句:
- DROP TABLE IF EXISTS `student`;
- CREATE TABLE `student` (
- `id` int(11) NOT NULL auto_increment,
- `name` varchar(255) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- DROP TABLE IF EXISTS `computer`;
- CREATE TABLE `computer` (
- `id` int(11) NOT NULL auto_increment,
- `name` varchar(255) NOT NULL,
- `student_id` int(11) ,
- foreign key (`student_id`) references student(`id`),
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Student.java:
- public class Student implements java.io.Serializable {
- private Integer id;
- private String name;
- private Computer computer;
- public Student() {
- }
- public Student(String name) {
- this.name = name;
- }
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Computer getComputer() {
- return computer;
- }
- public void setComputer(Computer computer) {
- this.computer = computer;
- }
- }
Computer.java:
- public class Computer implements java.io.Serializable {
- private Integer id;
- private Student student;
- private String name;
- public Computer() {
- }
- public Computer(String name) {
- this.name = name;
- }
- public Computer(Student student, String name) {
- this.student = student;
- this.name = name;
- }
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public Student getStudent() {
- return this.student;
- }
- public void setStudent(Student student) {
- this.student = student;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
Student.hbm.xml:
- <class name="com.domain.Student" table="student" catalog="onetoone">
- <id name="id" type="java.lang.Integer">
- <column name="id" />
- <generator class="native" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="name" not-null="true" />
- </property>
- <!-- class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的 -->
- <one-to-one cascade="delete,save-update" name="computer" class="com.domain.Computer" property-ref="student"></one-to-one>
- </class>
Computer.hbm.xml:
- <class name="com.domain.Computer" table="computer" catalog="onetoone">
- <id name="id" type="java.lang.Integer">
- <column name="id" />
- <generator class="native" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="name" not-null="true" />
- </property>
- <!-- many开头的是代表该表持有外键 -->
- <many-to-one name="student" class="com.domain.Student" unique="true">
- <column name="student_id" />
- </many-to-one>
- </class>