- 浏览: 342712 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (511)
- AgileMethodology (4)
- RDBMS (32)
- NoSQL (16)
- Java (27)
- Python (28)
- Maven (15)
- Linux (27)
- CommonUtils (13)
- IDE (8)
- JavaScript (17)
- jQuery (2)
- OSGi (2)
- JavaWeb (5)
- Spring (37)
- Struts2 (3)
- ORM (13)
- Ant (1)
- apache-tiles (1)
- FreeMarker (2)
- JSON (8)
- XML (1)
- JUnit (3)
- Lucene (1)
- Web Service (9)
- Design Pattern (13)
- Algorithm (21)
- JVM (14)
- Hadoop (16)
- Spark (5)
- Scala (31)
- Git (4)
- Server (3)
- Node.js (18)
- Concurrent (42)
- Lock (9)
- Collections (3)
- Network (11)
- MicroService (7)
- Docker (13)
- FP (20)
- spring.io (2)
- ELK (1)
- Kafka (5)
最新评论
0.pom.xml
...... <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <hibernate-version>3.6.10.Final</hibernate-version> <javassist-version>3.12.1.GA</javassist-version> <slf4j-nop-version>1.6.6</slf4j-nop-version> <mysql-connector-version>5.1.21</mysql-connector-version> </properties> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate-version}</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>${javassist-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>${slf4j-nop-version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-version}</version> </dependency> </dependencies> ......
1.schema.sql
drop table if exists idcard; drop table if exists student; create table idcard ( iid integer not null, num integer, primary key (iid) ); create table student ( sid integer not null auto_increment, name varchar(255), primary key (sid) );
表结构如下图所示
2.hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="format_sql">false</property> <!-- <mapping resource="org/fool/model/Student.hbm.xml" /> --> <!-- <mapping resource="org/fool/model/IdCard.hbm.xml" /> --> <mapping class="org.fool.model.Student" /> <mapping class="org.fool.model.IdCard" /> </session-factory> </hibernate-configuration>
这里使用Student表和IdCard表进行一对一关联
3.Student.java
package org.fool.model; 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.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @Entity @Table(name = "student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "sid") private int id; @Column(name = "name") private String name; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "student") @Fetch(FetchMode.SELECT) private IdCard idCard; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public IdCard getIdCard() { return idCard; } public void setIdCard(IdCard idCard) { this.idCard = idCard; } }
以上的annotation就相当于以下的Student.hbm.xml文件,可以进行对比一下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="org.fool.model.Student" table="student"> <id name="id" column="sid" type="integer"> <generator class="identity"> </generator> </id> <property name="name" column="name" type="string" /> <one-to-one name="idCard" class="org.fool.model.IdCard" cascade="all" fetch="select"></one-to-one> </class> </hibernate-mapping>
4.IdCard.java
package org.fool.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name = "idcard") public class IdCard { @Id @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "student")) @GeneratedValue(generator = "generator") @Column(name = "iid") private int id; @Column(name = "num") private int num; @OneToOne(fetch = FetchType.LAZY) @PrimaryKeyJoinColumn @Fetch(FetchMode.SELECT) private Student student; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
以上的annotation就相当于以下的IdCard.hbm.xml文件,可以进行对比一下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="org.fool.model.IdCard" table="idcard"> <id name="id" column="iid" type="integer"> <generator class="foreign"> <param name="property">student</param> </generator> </id> <property name="num" column="num" type="integer" /> <one-to-one name="student" class="org.fool.model.Student" fetch="select"></one-to-one> </class> </hibernate-mapping>
5.HibernateUtil.java
package org.fool.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure() .buildSessionFactory(); } catch (Exception ex) { System.err.println("构造SessionFactory异常发生: " + ex.getMessage()); } } public static Session openSession() { Session session = sessionFactory.openSession(); return session; } public static void closeSession(Session session) { if (null != session) { session.close(); } } }
6.HibernateTest.java
package org.fool.test; import org.fool.model.IdCard; import org.fool.model.Student; import org.fool.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class HibernateTest { public static void main(String[] args) throws Exception { // insert(); // selectStudent(); // updateStudent(); // delete(); } /** * 添加信息 */ public static void insert() { Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Student student = new Student(); student.setName("zhangsan"); IdCard idCard = new IdCard(); idCard.setNum(123456); student.setIdCard(idCard); idCard.setStudent(student); session.save(student); tx.commit(); } catch (Exception e) { e.printStackTrace(); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } } /** * 查询学生信息 */ public static void selectStudent() { Session session = HibernateUtil.openSession(); Transaction tx = null; Student student = null; try { tx = session.beginTransaction(); student = (Student) session.get(Student.class, 1); tx.commit(); } catch (Exception e) { e.printStackTrace(); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } System.out.println(student.getName()); System.out.println(student.getIdCard().getNum()); } /** * 更新学生信息 */ public static void updateStudent() { Session session = HibernateUtil.openSession(); Transaction tx = null; Student student = null; try { tx = session.beginTransaction(); student = (Student) session.get(Student.class, 1); student.setName("lisi"); tx.commit(); } catch (Exception e) { e.printStackTrace(); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } System.out.println(student.getName()); } /** * 级联删除 */ public static void delete() { Session session = HibernateUtil.openSession(); Transaction tx = null; Student student = null; try { tx = session.beginTransaction(); student = (Student) session.get(Student.class, 1); session.delete(student); tx.commit(); } catch (Exception e) { e.printStackTrace(); if (null != tx) { tx.rollback(); } } finally { HibernateUtil.closeSession(session); } } }
7.总结
主键关联:一对一默认使用的是立即加载,如果需要使用延迟加载,那么需要在one-to-one元素中将constrained属性设为true,并且将待加载的一方的class元素中lazy属性设为true(或者不去设置,因为该属性默认值是true);一对一加载时默认 使用左外连接,可以通过修改fetch属性为select,修改成每次发送一条select语句的形式。
发表评论
-
MyBatis工作流程
2019-08-12 10:46 459Reference https://www.cnblogs ... -
MyBatis一级缓存和二级缓存(转)
2017-08-31 20:26 259作者:little飞 出处:http:/ ... -
Spring MyBatis CRUD
2017-05-31 22:05 476原创转载请注明出处:http://agilestyle.i ... -
Hibernate常见术语、操作、区别
2017-03-02 22:08 408原创转载请注明出处:http://agilestyle.i ... -
Hibernate HQL, SQL查询及抓取策略
2013-04-10 09:53 13181.Maven Dependency <proje ... -
MyBatis CRUD Operations
2013-03-27 16:48 13651.Maven Dependency <proje ... -
Spring Hibernate CRUD
2013-03-21 14:21 12391.Maven Dependency <projec ... -
Hibernate 3和4的HibernateUtil
2013-02-16 16:19 1242Hibernate 3 1.Maven Dependen ... -
Hibernate getCurrentSession() vs openSession()
2012-12-21 12:30 8741、getCurrentSession()与openSe ... -
Hibernate Many to Many Annotation Example
2012-08-30 15:01 9671.schema.sql alter table stu ... -
Hibernate One to Many Annotation Example
2012-08-30 09:46 11590.pom.xml ...... <prope ... -
Hibernate 一对一映射之外键关联 Annotation Example
2012-08-29 16:39 8710.pom.xml ...... <proper ...
相关推荐
6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,...
7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...
1.1. 开始Hibernate之旅 1.2. 第一个持久化类 1.3. 映射cat 1.4. 与Cat同乐 1.5. 结语 2. 架构(Architecture) 2.1. 概况(Overview) 2.2. 实例状态 2.3. JMX整合 2.4. 对JCA的支持 3. 配置 3.1. 可编程的配置方式 ...
一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,涉及...
映射主键属性 @Id 注解可将实体Bean中某个属性定义为主键,使用@GenerateValue注解可以定义该标识符的生成策略。 • AUTO - 可以是 identity column, sequence 或者 table 类型,取决于不同底层的数据库 • TABLE ...
7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...
7.2.5. 一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...
一对多关联(One-to-many Associations) 7.3. 高级集合映射(Advanced collection mappings) 7.3.1. 有序集合(Sorted collections) 7.3.2. 双向关联(Bidirectional associations) 7.3.3. 三重关联...
6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 三重关联...
6.2.5. 一对多关联(One-to-many Associations) 6.3. 高级集合映射(Advanced collection mappings) 6.3.1. 有序集合(Sorted collections) 6.3.2. 双向关联(Bidirectional associations) 6.3.3. 双向关联,...
mybatis实战教程mybatis in action之四实现关联数据的查询 mybatis实战教程mybatis in action之五与spring3集成附源码 mybatis实战教程mybatis in action之六与Spring MVC 的集成 mybatis实战教程mybatis in action...