映射主键
如果实体类的标识属性( 映射成主键列〉是基本数据类型、基本类型的包装类、String 、Date 等类型,可以简单地使用@Id 修饰该实体属性即可。使用@Id 注解时无须指定任何属性。
如果希望Hibernate 为逻辑主键自动生成主键值,则还应该使用@GeneratedValue 来修饰实体的标识属性,使用@GeneratedValue 时可指定如图所示
import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;
import javax.persistence.metamodel.EntityType;
import java.util.Map;
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
ourSessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
Transaction tx = session.beginTransaction();
// 创建消息对象
News n = new News();
// 设置消息标题和消息内容
n.setTitle("疯狂Java联盟成立了");
n.setContent("疯狂Java联盟成立了,"
+ "网站地址http://www.crazyit.org");
// 保存消息
session.save(n);
// 提交事务
tx.commit();
} finally {
session.close();
}
}
}
import javax.persistence.*;
@Entity
@Table(name="news_inf")
public class News
{
// 消息类的标识属性
@Id
// 定义主键生成器
@TableGenerator(name="newsGen" , table="NEWS_ID_GEN",
pkColumnName="gen_key", valueColumnName="gen_value",
pkColumnValue="news_id")
// 使用GenerationType.TABLE主键生成策略
@GeneratedValue(strategy=GenerationType.TABLE
, generator="newsGen")
private Integer id;
// 消息标题
private String title;
// 消息内容
private String content;
// id的setter和getter方法
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return this.id;
}
// title的setter和getter方法
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
// content的setter和getter方法
public void setContent(String content)
{
this.content = content;
}
public String getContent()
{
return this.content;
}
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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/hibernate?serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<!--指定数据库方言-->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- DB schema will be updated if needed -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--在控制台显示SQL语句-->
<property name="show_sql">true</property>
<!--将SQL脚本中语句格式化在输出-->
<property name="hibernate.format_sql">true</property>
<!--罗列所有的持久化类-->
<mapping class="News"/>
</session-factory>
</hibernate-configuration>
映射集合属性
Hibernate 要求持久化集合值字段必须声明为接口,实际的接口可以是java.util.Set 、java.util.Collection java.util.List 、java. util.Map 、java . util. SortedSet 、java.util.SortedMap 等,甚至是自定义类型(只需要实现org. hi bemate. usertype. U serCo llecti on Type 接口即可〉。
Hibernate Hibernate 之所以要求用集合接口来声明集合属性,是因为当程序持久化某个实例时午, Hibernate 会自动把程序中的集合实现类替换Hibernate 自己的集合实现类,因此不要试图把H ibernate 集合属性强制类型转换为集合实现类,Hash Set 、HashMap 等,但可以转换为Set 、Map 等集合,因为Hibernate自己的集合类也实现了Map 、Set 等接口。
不管哪种类型的集合属性,都统一使用@E lementCo llection 注解进行映射。使用@ElementCollection注解时可指定如图·所示的属性。
- Hibernate 使用标准的@CollectionTable 注解映射保存集合属性的表
- @Join Column 注解专门用于定义外链
有序集合映射
SortedSet
hibernate.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2b8</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- DB schema will be updated if needed -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="Person"/>
</session-factory>
</hibernate-configuration>
Person.java
import java.util.*;
import javax.persistence.*;
import org.hibernate.annotations.SortNatural;
/**
* Description:
* <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
* <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee [email protected]
* @version 1.0
*/
@Entity
@Table(name="person_inf")
public class Person
{
@Id @Column(name="person_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
// 标识属性
private Integer id;
private String name;
private int age;
// 有序集合属性
@ElementCollection(targetClass=String.class)
// 映射保存集合元素的表
@CollectionTable(name="training_inf",
joinColumns=@JoinColumn(name="person_id" , nullable=false))
// 定义保存集合元素的数据列
@Column(name="training_name" , nullable=false)
// 使用@SortNatural指定使用自然排序
@SortNatural
private SortedSet<String> trainings
= new TreeSet<>();
// id的setter和getter方法
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return this.id;
}
// name的setter和getter方法
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
// age的setter和getter方法
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
// trainings的setter和getter方法
public void setTrainings(SortedSet<String> trainings)
{
this.trainings = trainings;
}
public SortedSet<String> getTrainings()
{
return this.trainings;
}
}
Main.java
import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;
import javax.persistence.metamodel.EntityType;
import java.util.Map;
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
ourSessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
Transaction tx = session.beginTransaction();
// 创建Person对象
Person wawa = new Person();
wawa.setAge(21);
wawa.setName("crazyit.org");
// 为trainings集合属性添加2个元素
wawa.getTrainings().add("Wild Java Camp");
wawa.getTrainings().add("Sun SCJP");
session.save(wawa);
Person p = (Person)session.get(Person.class , 1);
// 再次添加一个集合元素
p.getTrainings().add("CCNP");
tx.commit();
}
finally {
session.close();
}
}
}
运行结果