1、主要笔记
联合主键:
单独写成一个类,StudentPK.java
将pk当作student的一个属性,这个属性可以设置两个参数
在xml中也要改:
组键作为联合主键
注意继承了序列化类:
集群的时候用,内存满了用硬盘的时候用
联合主键要重写equals和hasCode方法
哈希码:
哈希表当作一个数组,如果两个对象哈希码相同,就被装在同一个位置,类似一个链表,
查找的时候就会先通过哈希码找到大致位置,然后通过equals判断,相同就是同一个对象
注释实现联合主键有三种形式:
1,@Embeddable,@Id
范例中的样子
2,@EmbeddedId
加在pk那个方法上就行了
3,@Id,@Id,@IdClass(value="TeacherPK.class")
id和name都保留,分别加上@Id,然后在Teacher类上面加上@IdClass(value="TeacherPK.class")
2、log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
3、hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">haizhu</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup:创建或者修改表 -->
<!-- 一共有create,update,validate,create-drop 四个模式 -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/haizhu/model/Student.hbm.xml"/>
<mapping class="com.haizhu.model.Teacher"/>
</session-factory>
</hibernate-configuration>
4、HibernateSessionFactory.java
package com.haizhu.hb;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
5、Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.haizhu.model.Student" table="h_student">
<composite-id name="pk" class="com.haizhu.model.StudentPK">
<key-property name="id" column="s_id"></key-property>
<key-property name="name" column="s_name"></key-property>
</composite-id>
<property name="age" column="s_age"/>
</class>
</hibernate-mapping>
6、Student.java
package com.haizhu.model;
public class Student {
private StudentPK pk;
private int age;
public StudentPK getPk() {
return pk;
}
public void setPk(StudentPK pk) {
this.pk = pk;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
7、StudentPk.java
package com.haizhu.model;
public class StudentPK implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
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;
}
//最好重写equals和hasCode方法
@Override
public boolean equals (Object o){
if(o instanceof StudentPK){
StudentPK pk = (StudentPK)o;
if(this.id == pk.getId()&&this.name.equals(pk.getName())){
return true;
}
}
return false;
}
public int hasCode(){
return this.name.hashCode();
}
}
8、StudentTest.java
package com.haizhu.model;
import org.hibernate.Session;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.haizhu.hb.HibernateSessionFactory;
import com.haizhu.model.Student;
public class StudentTest{
/**
*
*/
Session sess = null;
@Before
public void setUp() throws Exception {
sess = HibernateSessionFactory.getSession();
System.out.println("增加学生:");
}
@Test
public void test() {
StudentPK pk = new StudentPK();
pk.setId(11);
pk.setName("王五");
Student s = new Student();
s.setAge(25);
s.setPk(pk);
sess.beginTransaction();
sess.save(s);
sess.getTransaction().commit();
sess.close();
}
@AfterClass
public static void afterClass(){
System.out.println("程序顺利结束!");
}
}
9、Teacher.java
package com.haizhu.model;
import java.util.Date;
import javax.persistence.*;
@Entity
@Table(name= "h_teacher")
public class Teacher {
private TeacherPK pk;
private String title;
private String yourwifename;
private Date date;
private Sex sex;
/**
* @Id 映射主键属性,这里采用uuid的主键生成策略
* @GeneratedValue —— 注解声明了主键的生成策略。该注解有如下属性
* strategy 指定生成的策略,默认是GenerationType. AUTO
* GenerationType.AUTO 主键由程序控制
* GenerationType.TABLE 使用一个特定的数据库表格来保存主键
* GenerationType.IDENTITY 主键由数据库自动生成,主要是自动增长类型
* GenerationType.SEQUENCE 根据底层数据库的序列来生成主键,条件是数据库支持序列
* generator 指定生成主键使用的生成器
*
* 更改主键为自增长:alter table A modify column a not null auto_increment;
*
*/
//第二种方法是:下面的Id换成EmbeddedId就可以省略TeacherPK中的Embeddable注释了。
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public TeacherPK getPk() {
return pk;
}
public void setPk(TeacherPK pk) {
this.pk = pk;
}
@Basic
@Column(name="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Transient
public String getYourwifename() {
return yourwifename;
}
public void setYourwifename(String yourwifename) {
this.yourwifename = yourwifename;
}
@Temporal(TemporalType.DATE)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Enumerated(EnumType.STRING)
public Sex getSex() {
return sex;
}
public void setSex(Sex sex) {
this.sex = sex;
}
}
10、Sex.java
package com.haizhu.model;
public enum Sex {
man,lady
}
11、TeacherPK.java
package com.haizhu.model;
import javax.persistence.Embeddable;
@Embeddable
public class TeacherPK implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
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;
}
//最好重写equals和hasCode方法
@Override
public boolean equals (Object o){
if(o instanceof TeacherPK){
TeacherPK pk = (TeacherPK)o;
if(this.id == pk.getId()&&this.name.equals(pk.getName())){
return true;
}
}
return false;
}
public int hasCode(){
return this.name.hashCode();
}
}
12、TeacherTest.java
package com.haizhu.model;
import java.util.Date;
import com.haizhu.hb.*;
import com.haizhu.model.Teacher;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
public class TeacherTest {
@Before
public void setUp() throws Exception {
System.out.println("增加老师:");
}
@Test
public void test() {
TeacherPK pk = new TeacherPK();
pk.setName("海竹");
//这里Id是自动增长形式,就不需要输入了
//pk.setId(15);
Teacher t = new Teacher();
t.setPk(pk);
t.setTitle("甲");
t.setYourwifename("小丽");
t.setDate(new Date());
t.setSex(Sex.man);
Session sess = HibernateSessionFactory.getSession();
sess.beginTransaction();
sess.save(t);
sess.getTransaction().commit();
}
}