??xml version="1.0" encoding="utf-8" standalone="yes"?>
]]>
先从配置文g开始:
源码Q?a href="/Files/Good-Game/springAop.rar">springAop.rar
需要jar
<classpath>
<classpathentry kind="src" path="java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/aspectjrt.jar"/>
<classpathentry kind="lib" path="lib/aspectjweaver.jar"/>
<classpathentry kind="lib" path="lib/spring.jar"/>
<classpathentry kind="lib" path="lib/spring-sources.jar"/>
<classpathentry kind="lib" path="lib/commons-logging-1.0.4.jar"/>
<classpathentry kind="lib" path="lib/cglib-nodep-2.1_3.jar"/>
<classpathentry kind="lib" path="lib/hibernate3.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.11.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="lib" path="lib/dom4j-1.6.1.jar"/>
<classpathentry kind="lib" path="lib/commons-collections-2.1.1.jar"/>
<classpathentry kind="lib" path="lib/mysql.jar"/>
<classpathentry kind="lib" path="lib/jta.jar"/>
<classpathentry kind="lib" path="lib/antlr-2.7.6.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
spring 配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- daoCalss : extends HibernateDaoSupport implements BeanDao -->
<bean id="beanDao" class="dao.imp.BeanDaoImp">
<property name="sessionFactory">
<ref bean="sessionFactory"></ref>
</property>
</bean>
<!-- hibernate3 sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- spring ?hibernate 联系 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<!-- aop 与事务联p aopBean<->txAdvice -->
<aop:config>
<!-- 逻辑拦截 -->
<aop:pointcut id="aopBean" expression="execution(* *.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="aopBean" />
</aop:config>
<!-- 事务适配器?/span>-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 事务原子 具体Ҏq行什么事务?/span>-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
</beans>
hibernate 配置
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="asdf">
<property name="hibernate.dialect">mysql</property>
<property name="myeclipse.connection.profile">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost/aop
</property>
<property name="show_sql">true</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="bean/UnitBean.hbm.xml" />
</session-factory>
</hibernate-configuration>
dao c(接口Q?br />
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import bean.UnitBean;
import dao.BeanDao;
public class BeanDaoImp extends HibernateDaoSupport implements BeanDao{
public void addBean(UnitBean unitBean) {
this.getHibernateTemplate().save(unitBean);
}
public List<UnitBean> getBeanByAll() {
return this.getHibernateTemplate().find(" from "+UnitBean.class.getName());
}
public void removeBean(long beanId) {
this.getHibernateTemplate().delete(
getHibernateTemplate().get(UnitBean.class, beanId)
);
}
}
Main c?br />
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.BeanDao;
import bean.UnitBean;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
BeanDao dao = (BeanDao) ctx.getBean("beanDao");
UnitBean bean = new UnitBean();
bean.setName("xx");
bean.setPass("11");
dao.addBean(bean);
for(UnitBean unitBean : dao.getBeanByAll() ){
System.out.println( unitBean.getId() );
}
dao.removeBean(bean.getId());
}
}
Hibernate: select unitbean0_.id as id0_, unitbean0_.name as name0_, unitbean0_.pass as pass0_ from bean unitbean0_
1
Hibernate: select unitbean0_.id as id0_0_, unitbean0_.name as name0_0_, unitbean0_.pass as pass0_0_ from bean unitbean0_ where unitbean0_.id=?
Hibernate: delete from bean where id=?
]]>
]]>
* d 问题 和 选项
* @throws Exception
*/@Test
public void testQu() throws Exception {
Session session = HibernateUtil.currentSession();
Transaction tr = session.beginTransaction();
//U联d
Set options = new HashSet();
Options op1 = new Options();
op1.setName("op1");
options.add(op1);
Options op2 = new Options();
op2.setName("op2");
options.add(op2);
Options op3 = new Options();
op3.setName("op3");
options.add(op3);
Problems problems = new Problems();
problems.setName("problem_1");
problems.setOptions(options);
problems.setTdesc("tdesc");
problems.setType(1);
Long ll = (Long)session.save(problems);
System.out.println(ll);
tr.commit();
mysql> select * from options ;
+----+------------+--------+------+---------+
| id | problemsid | answer | name | visible |
+----+------------+--------+------+---------+
| 1 | 1 | NULL | op2 | 0 |
| 2 | 1 | NULL | op3 | 0 |
| 3 | 1 | NULL | op1 | 0 |
+----+------------+--------+------+---------+
3 rows in set (0.00 sec)
mysql> select * from problems ;
+----+-----------+------+-------+------------+---------+
| id | name | type | tdesc | questionid | visible |
+----+-----------+------+-------+------------+---------+
| 1 | problem_1 | 1 | tdesc | NULL | 0 |
+----+-----------+------+-------+------------+---------+
1 row in set (0.00 sec)
//U联删除
tr.begin();
session.delete( session.get(Problems.class,ll) );
tr.commit();
mysql> select * from problems ;
Empty set (0.00 sec)
mysql> select * from options ;
Empty set (0.00 sec)
HibernateUtil.closeSession();
}
Optionsc?br />
/**
* @hibernate.many-to-one
* cascade = "save-update"
* column = "Problemsid"
* class = "com.zhongqi.domain.Problems"
* @return
*/
public Problems getProblems() {
return problems;
}
............
Problems c?br />
* @hibernate.set
* cascade="all-delete-orphan"
* inverse = "false"
* lazy = "true"
* @hibernate.collection-key column = "problemsid"
* @hibernate.collection-one-to-many class = "com.zhongqi.domain.Options"
* @return
*/
public Set getOptions() {
return options;
}
]]>
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| type | varchar(255) | NO | | NULL | |
| title | varchar(255) | YES | | NULL | |
| inputTime | datetime | YES | | NULL | |
| content | blob | YES | | NULL | |
| recommended | bit(1) | YES | | NULL | |
| categories | varchar(255) | YES | | NULL | |
+-------------+--------------+------+-----+---------+-------+
2.代码
Session sess = HibernateSessionFactory.getSession();
Transaction tr = sess.beginTransaction();
LotteryNew nn = new LotteryNew();
nn.setInputTime(new Date());
nn.setCategories("t");
nn.setTitle("new");
nn.setRecommended(true);
Blob bo = Hibernate.createBlob("ggggg".getBytes());
nn.setContent(bo);
sess.save(nn);
tr.commit();
HibernateSessionFactory.closeSession();
//修改
sess = HibernateSessionFactory.getSession();
tr = sess.beginTransaction();
LotteryNew lo = (LotteryNew) sess.get(LotteryNew.class, nn.getId());
Blob bog = Hibernate.createBlob("xxxxx".getBytes());
lo.setContent(bog);
tr.commit();
HibernateSessionFactory.closeSession();
//查找
sess = HibernateSessionFactory.getSession();
LotteryNew lo2 = (LotteryNew) sess.get(LotteryNew.class, lo.getId());
InputStream in = lo2.getContent().getBinaryStream() ;
byte[] bbr = new byte[in.available()];
in.read(bbr);
System.out.println(new String(bbr));
HibernateSessionFactory.closeSession();
]]>
]]>
开发过E描qͼ
1.使用 MyEclipes -> uml 创徏cd
2.?Generate java Code Ҏcd生成 java文g
3.使用 Xdoclet d Hbn 标签
4.配置myEclipes -> XDoclet 自动生成 mapping.hbn.xml
5.使用myEclipes 把项目{化成 hibernate 目
6.使用 org.hibernate.tool.hbm2ddl.SchemaExport
开发过E好处:
1Q完全是面向对象Q不需要写xml配置文g(XDoclet);
2)目后期修改Ҏ面对uml
3Q用myEclipes q些都不用去找,直接拿来?uml,XDoclet,hibernate ..)
下面来?例?
1.MyEclipes 使用 uml 参?>MyEclipse 5.5 UML 入门视频 (作者:BeanSoft)
2.由uml生成cL?
3.先?eclipes?快键Ҏ?get/set ҎQ?cL件文件添?hbn XDoclet的注?br />
/**
* @hibernate.class table="t1oo"
*/
public class T1oo {
public int id;
public String name;
public int avg;
/**
* @hibernate.property
* column="avg"
* length="4"
* not-null="true"
*/
public int getAvg() {
return avg;
}
public void setAvg(int avg) {
this.avg = avg;
}
/**
* @hibernate.id
* column="id"
* generator-class="hilo"
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
* @hibernate.property
* column="name"
* not-null="true"
* @return
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4.用myEclipes 生成 XDoclet
在项目点右键-> properties -> MyEclipse-XDoclet ->
在Configuration I白初点右键 ?add standard -> ... hbn 后面不太好描q?可以查下很简单的 。配|好了运行后可以看?多了 ?T1oo.hbm.xml 文g;
5.myEclipes + hbn ׃多说?br />6. hbn2java:
HibernateSessionFactory.currentSession();
HibernateSessionFactory.closeSession();
Field[] ff = HibernateSessionFactory.class.getDeclaredFields();
Field fie = null ;
for(int i=0;i<ff.length;i++){
if( ff[i].getType().equals( Configuration.class ) ){
fie = ff[i];
}
}
fie.setAccessible(true);
Configuration cfg = (Configuration)fie.get(HibernateSessionFactory.class);
cfg.addInputStream( this.getClass().getResourceAsStream("/bean/T1oo.hbm.xml") );
//
SchemaExport dbExport = new SchemaExport(cfg);
dbExport.setOutputFile("c:\\db\\test.txt");
dbExport.create(true, true);
}
sqlQ?br />drop table if exists t1oo
drop table if exists hibernate_unique_key
create table t1oo (
id integer not null,
avg integer not null,
name varchar(255) not null,
primary key (id)
)
create table hibernate_unique_key (
next_hi integer
)
insert into hibernate_unique_key values ( 0 )
效果Q?br />mysql> show tables;
+----------------------+
| Tables_in_hbn |
+----------------------+
| hibernate_unique_key |
| t1oo |
+----------------------+
2 rows in set (0.00 sec)
]]>
1.单条select延迟加蝲
while(it.hasNext()){
T1oo t1 = (T1oo)it.next();
t1.getName();
}
/*q行语句 n+1
q就只加?id
Hibernate: select t1oo0_.id as col_0_0_ from t1oo t1oo0_
此是?t1.getName(); 延迟加蝲?
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
*/
2.U连查询Q?br />1)set排序 <set ... order-by="avg desc" ...> 从大到小
2Qbatch-size="10" 用法?
select * from t2oo where aid in (?,?,?....)
3)
如果惛_略gq,q有一定逻辑全部加蝲Q这有两中解军_法:
1).内连
-> from t1oo t1oo0_ inner join t2oo t2ooset1_ on t1oo0_.id=t2ooset1_.aid;
+----+-----------+----+-----+------+---------+
| id | name | id | avg | aid | version |
+----+-----------+----+-----+------+---------+
| 1 | liukaiyi | 1 | 23 | 1 | 1 |
| 1 | liukaiyi | 2 | 24 | 1 | 1 |
| 1 | liukaiyi | 3 | 25 | 1 | 1 |
| 2 | liukaiyi2 | 4 | 26 | 2 | 0 |
+----+-----------+----+-----+------+---------+
while(it.hasNext()){
T1oo t1 = (T1oo)it.next();
System.out.println(t1.getName());
for(Iterator itr=t1.getT2ooSet().iterator();itr.hasNext(); ){
T2oo t2 = (T2oo)itr.next();
System.out.println(" "+ t2.getAvg() );
}
}
liukaiyi
24
23
25
]]>
<property name="hibernate.cache.use_query_cache">true</property>
<mapping resource="hbn/bean/T1oo.hbm.xml" />
<mapping resource="hbn/bean/T2oo.hbm.xml" />
<class-cache class="hbn.bean.T1oo" usage="read-only" />
<collection-cache collection="hbn.bean.T1oo.t2ooSet" usage="read-only" />
<class-cache class="hbn.bean.T2oo" usage="read-only" />
在src根目录下 ehcache.xml
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000" //最大缓存数?/font>
eternal="false"Q?-- ~存是否持久 --Q?/font>
timeToIdleSeconds="120" Q?-- 当缓存闲|nU后销?--Q?/font>
timeToLiveSeconds="120"Q?-- 当缓存存znU后销?-Q?/font>
overflowToDisk="true"Q?-- 是否保存到磁盘,当系l当机时--Q?/font>
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<cache
name="hbn.bean.T1oo"
maxElementsInMemory="450"
eternal="false"
timeToLiveSeconds="600"
overflowToDisk="true"/>
</ehcache>
试Q?br />
System.out.println( getT1ooAll() );
Thread.sleep(2*1000);
System.out.println( getT1ooAll() );
}
控制台输?br />
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=?
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=?
24 : 23 : 25 : 2
//在这~存成功 没向数据库提?sql语句
24 : 23 : 25 : 2
]]>
所用到知识点:
一般jdk
|-U有属性反?br />|-序列?br />|-正则表达使用
|-多线E?br />|-dom4j的xmld
|+hibernate
|-拦截?br /> |-一个Session工厂同时q接不同数据库(本文关键Q?br /> |-oracle Blob 存取
{?.......
需求功能介l:
为性能考虑Q单一服务器改成集(每太服务器数据允许在一定时间内保持相步Q,l出的修Ҏ间短Q不q代码持久层比较l一Qhibernate 感谢天还好是她! Q。网l连接不E_Q铁路内|!Q?br />
完成后效果:
当网l连接成功时Q多数据库的同步?br /> ?/font>|络q接p|Ӟ本地应用E序q用hibernate拦截器拦截正操作对象q记录下操作动作Q序列化到本地时局?z_jcyy_tb 表中。表数据属性ؓQid,inputdate(记录旉),objectQ序列对象),action(操作动作)。ƈ安一定时间测试连接。如果成功,d z_jcyy_tb 表中数据 反序列化 再同步到 其他数据库中?br />
代码说明Q?br />1.新Session 建立
hibernate.cfg.xml 在文?/font><session-factory>中添?
<property name="connection.username_b">jcyy</property>
<property name="connection.password_b">jcyy</property>
private static String use_b = null ;
private static String pass_b = null ;
private static String dirver_b = null ;
static {try {
//取得hibernate.cfg.xml逻辑路径Q和原来E序兌上?
Field field = SessionManager.class.getDeclaredField("CONFIG_FILE_LOCATION");
field.setAccessible( true );
String path = (String) field.get(SessionManager. class );
//通过 dom4j 加蝲 配置文g
Document docT = new SAXReader().read( TBDao.class.getResourceAsStream(path) );
//正则+xpathd 在hbn文g中加入的<property name="..._b"> 的属?/font>
String xpath = "/hibernate-configuration/session-factory/property[@name='XPATH_I']" ;
Pattern p = Pattern.compile("(XPATH_I)");
Matcher ma = p.matcher(xpath);
url_b = DocumentHelper.createXPath( ma.replaceAll("connection.url_b") ).selectSingleNode(docT).getText();
use_b = DocumentHelper.createXPath( ma.replaceAll("connection.username_b")).selectSingleNode(docT).getText();
pass_b = DocumentHelper.createXPath( ma.replaceAll("connection.password_b")).selectSingleNode(docT).getText();
dirver_b = DocumentHelper.createXPath( ma.replaceAll("connection.driver_class")).selectSingleNode(docT).getText();
} catch (Exception e) {e.printStackTrace();}}
//利用hbn的SessionFactory得到 openSession(Connection); 打开异地数据库连接?
//利用U有反射得到 加蝲完成的SessionFactory
public Session openSessionb(){
try {
Class.forName(dirver_b);
Connection conn = DriverManager.getConnection(url_b,use_b,pass_b);
Field[] fields = SessionManager.class.getDeclaredFields();
Field field = null ;
for(int i=0;i<fields.length;i++){
if( SessionFactory.class.equals( fields[i].getType() ) )
field = fields[i];
}
field.setAccessible(true);
SessionFactory sessionFactory = (SessionFactory) field.get(SessionManager.class );
return sessionFactory.openSession(conn);
} catch (Exception e) {
System.out.println("--没有q接到L?openSessionb)--");
return null ;
}
}
2.异地数据同步p|后动作?TBDao->save() ȝ状态到数据?br />
Session session = null ;
try {
session = SessionManager.currentSession(null,null);
Transaction tr = session.beginTransaction();
ZJcyyTb zj = new ZJcyyTb();
zj.setAction(action);
zj.setInputdate(new Date());
session.save(zj);
session.flush();
session.refresh(zj,LockMode.UPGRADE);
//oracle Blob数据持久 请参?->序列化和反序列化对象?数据?/a>
zj.setObject( new ObjectConvert().ObjectToBlob(obj) );
tr.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(session!=null&& session.isOpen() )session.close();
}
}
3,p|后又成功q接?Q线E实玎ͼ TBDao->action()
int is_count = 0 ;
Session session = null ;
try {
//得到本地Session 查看是否有连接失败后序列动作被保?/font>
session = SessionManager.currentSession(null,null);
Transaction tr = session.beginTransaction();
Connection conn = session.connection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select count(*) from z_jcyy_tb");
rs.next();
is_count = rs.getInt(1);
tr.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(session!=null&& session.isOpen() )session.close();
}
return is_count ;
}
public boolean action(){
int isSql = 0 ;
ObjectConvert oc = new ObjectConvert();
Session session = null ;
Session session_b = null ;
try {
//有失败连接动作后试 q程数据库?
if( (isSql=isSql())>0 ){
session = SessionManager.currentSession(null,null);
//q程数据库连接?
//如果成功q接Qz_jcyy_tb表中数据同步到其他数据库?/font>
session_b = openSessionb();
if(session_b!=null){
Transaction tr_b = session_b.beginTransaction();
Transaction tr = session.beginTransaction();
Query qu = session.createQuery(" from ZJcyyTb t order by t.inputdate");
for(int i=0;i<=isSql/10;i++){
qu.setFirstResult(i*10);
qu.setMaxResults(10);
List list = qu.list();
for(Iterator it=list.iterator();it.hasNext();){
ZJcyyTb tb = (ZJcyyTb)it.next();
Object obj = null ;
obj = oc.BlobToObject(tb.getObject(),obj);
if(obj!=null){
String action = tb.getAction();
if(action.equals( TBDao.DELETE )){
session_b.delete(obj);
}
if(action.equals( TBDao.INSERT )){
session_b.save(obj);
}
if(action.equals( TBDao.UPDATE )){
session_b.update(obj);
}
}
session.delete(tb);
tr.commit();
}
}
tr_b.commit();
}
} return true ;
} catch (Exception e) {
System.out.println("--没有q接到L?action)--");
}finally{
if(session_b!=null&&session_b.isOpen())session_b.close();
if(session!=null&& session.isOpen() )session.close();
SessionManager.closeSession();
}
return false ;
}
4.hbn 拦截?->Interceptor
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.hibernate.CallbackException;
import org.hibernate.EntityMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.type.Type;
import com.jjm.rlzy.dao.TBDao;
public class TestInterceptor implements Interceptor,Serializable{
static private boolean isConn_b = false ;
static private TBDao tb = new TBDao();
//U程 一分钟 连接失?同步
static{
new Thread(new Runnable(){
public void run() {
while(true){
isConn_b = tb.action();
try {
Thread.sleep(60*1000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}
}).start();
}
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
Session session = null ;
try {
if(isConn_b){
session = tb.openSessionb();
Transaction tr = session.beginTransaction();
session.update(entity);
tr.commit();
}else{
tb.save(entity,TBDao.UPDATE);
}
} catch (Exception e) {
e.printStackTrace() ;
tb.save(entity,TBDao.UPDATE);
isConn_b = false ;
}finally{
if(session!=null)session.close();
// 拦截器中 l对不能有这?-> SessionManager.closeSession();
}
return false;
}
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
Session session = null ;
try {
if(isConn_b){
session = tb.openSessionb();
Transaction tr = session.beginTransaction();
session.save(entity);
tr.commit();
}else{
tb.save(entity,TBDao.INSERT);
}
} catch (Exception e) {
e.printStackTrace() ;
tb.save(entity,TBDao.INSERT);
isConn_b = false ;
}finally{
if(session!=null)session.close();
}
return false;
}
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
Session session = null ;
try {
if(isConn_b){
session = tb.openSessionb();
Transaction tr = session.beginTransaction();
session.delete(entity);
tr.commit();
}else{
tb.save(entity,TBDao.DELETE);
}
} catch (Exception e) {
e.printStackTrace() ;
tb.save(entity,TBDao.DELETE);
isConn_b = false ;
}finally{
if(session!=null)session.close();
}
}
................................
}
后记Q?br />׃一些原因代码写的有些简陋,但功能实玎ͼ表达的的意思也q可以(自己有点 ‘买瓜了’哈哈!Q。我写出来的目的希望大家能共同进步,q等大家拍砖?Q)
]]>
import
java.io.Serializable;
import
java.util.HashSet;
import
java.util.Iterator;
import
java.util.Set;
import
org.hibernate.CallbackException;
import
org.hibernate.EntityMode;
import
org.hibernate.Interceptor;
import
org.hibernate.Transaction;
import
org.hibernate.type.Type;
public
class
TestInterceptor
implements
Interceptor,Serializable{
private
Set inserts
=
new
HashSet();
private
Set updates
=
new
HashSet();
//
Session初化一个持久对?如果q方法中改变了对象属性就q回true 否则null
public
boolean
onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException {
return
false
;
}
//
Session flush()中检查到脏数据是调用 如:tr.commit() ....
public
boolean
onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
throws
CallbackException {
updates.add(entity);
return
false
;
}
//
Session Save() 当修改了对象属性返回true
public
boolean
onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException {
inserts.add(entity);
return
false
;
}
//
delete
public
void
onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException {
}
//flush() 之前调用
public
void
preFlush(Iterator entities)
throws
CallbackException {
}
//
flush() 执行SQL语句之后调用
public
void
postFlush(Iterator entities)
throws
CallbackException {
try
{
for
(Iterator it
=
updates.iterator();it.hasNext();){
System.out.println(
"
update=
"
+
it.next() );
}
for
(Iterator it
=
inserts.iterator();it.hasNext();){
System.out.println(
"
insert
"
+
it.next() );
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
public
Boolean isTransient(Object entity) {
//
TODO Auto-generated method stub
return
null
;
}
//军_Session中那些对象是脏数?如果null Session使用默认处理脏数?/span>
public
int
[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
return
null
;
}
// 当Session构造实体类对象前调?/span>
public
Object instantiate(String entityName, EntityMode entityMode, Serializable id)
throws
CallbackException {
return
null
;
}
public
String getEntityName(Object object)
throws
CallbackException {
//
TODO Auto-generated method stub
return
null
;
}
public
Object getEntity(String entityName, Serializable id)
throws
CallbackException {
//
TODO Auto-generated method stub
return
null
;
}
public
void
afterTransactionBegin(Transaction tx) {
//
TODO Auto-generated method stub
}
public
void
beforeTransactionCompletion(Transaction tx) {
//
TODO Auto-generated method stub
}
public
void
afterTransactionCompletion(Transaction tx) {
//
TODO Auto-generated method stub
}
}
试
import
java.lang.reflect.Field;
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
hbn.HibernateSessionFactory;
import
hbn.bean.T2oo;
import
junit.framework.TestCase;
public
class
TestIC
extends
TestCase {
private
SessionFactory sessionFactory;
protected
void
setUp()
throws
Exception {
super
.setUp();
//
利用java反射得到 HibernateSessionFactory ->
//
private static org.hibernate.SessionFactory sessionFactory;
//
要模拟 ƈ发 要 HibernateSessionFactory 得出的 有 threadLocal 不行
HibernateSessionFactory.currentSession();
HibernateSessionFactory.closeSession();
Field field
=
HibernateSessionFactory.
class
.getDeclaredField(
"
sessionFactory
"
);
field.setAccessible(
true
);
sessionFactory
=
(SessionFactory) field.get(HibernateSessionFactory.
class
);
}
public
void
testInc()
throws
Exception {
TestInterceptor intx
=
new
TestInterceptor();
//
加蝲拦截?/span>
Session session
=
sessionFactory.openSession(intx);
Transaction tr
=
session.beginTransaction();
T2oo t2
=
new
T2oo(
23
);
session.save(t2);
t2.setAvg(
new
Integer(
99
));
tr.commit();
}
}
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
Hibernate: update t2oo set version=?, avg=?, aid=? where id=? and version=?
//拦截到的
update=hbn.bean.T2oo@277
inserthbn.bean.T2oo@277
]]>
protected
void
setUp()
throws
Exception {
super
.setUp();
//
利用java反射得到 HibernateSessionFactory ->
//
private static org.hibernate.SessionFactory sessionFactory;
//
要模拟 ƈ发 要 HibernateSessionFactory 得出的 有 threadLocal 不行
//
要?/span>
HibernateSessionFactory.currentSession();
HibernateSessionFactory.closeSession();
Field field
=
HibernateSessionFactory.
class
.getDeclaredField(
"
sessionFactory
"
);
field.setAccessible(
true
);
sessionFactory
=
(SessionFactory) field.get(HibernateSessionFactory.
class
);
}
protected
void
tearDown()
throws
Exception {
super
.tearDown();
}
悲观?
* +----+------+
* | id | name |
* +----+------+
* | 4 | xx1 |
* +----+------+
*/
public
void
ctestLock()
throws
Exception {
//
insert test Data 试数据
Session seInsert
=
sessionFactory.openSession();
Transaction tr
=
seInsert.beginTransaction();
T1oo testUse
=
testUse
=
new
T1oo();
testUse.setName(
"
liukaiyi_test
"
);
seInsert.save(testUse);
tr.commit();
System.out.println(
"
**************Test Use Bean : insert*******************
"
);
seInsert.close();
Integer testId
=
testUse.getId();
//q发模拟
Session session1
=
sessionFactory.openSession();
Session session2
=
sessionFactory.openSession();
final
Transaction tr1
=
session1.beginTransaction();
Transaction tr2
=
session2.beginTransaction();
Query qu1
=
session1.createQuery(
"
from T1oo t1oo where t1oo.name='liukaiyi_test'
"
);
Query qu2
=
session2.createQuery(
"
from T1oo t1oo where t1oo.name='liukaiyi_test'
"
);
//加悲观锁
qu1.setLockMode(
"
t1oo
"
,LockMode.UPGRADE);
final
Object bean1
=
qu1.uniqueResult();
Object bean2
=
qu2.uniqueResult();
T1oo t1oo2
=
(T1oo)bean2;
t1oo2.setName(
"
run1
"
);
new
Thread(
new
Runnable(){
public
void
run() {
try
{
System.out.println(
"
********解锁准备*********
"
);
Thread.sleep(
10
*
1000
);
T1oo t1oo1
=
(T1oo)bean1;
t1oo1.setName(
"
run2
"
);
tr1.commit();
System.out.println(
"
********解锁成功t*********
"
);
}
catch
(InterruptedException e) {e.printStackTrace();}
}
}
).start();
/
/q里?{待十秒?tr1解锁 /
tr2.commit();
session1.close();
session2.close();
//
delete Test Date 删除试数据
Session seDelete
=
sessionFactory.openSession();
Transaction trD
=
seDelete.beginTransaction();
Object obj
=
seDelete.createQuery(
"
from T1oo t where t.id=:id
"
).
setInteger(
"
id
"
,testId.intValue()).
uniqueResult();
seDelete.delete(obj);
trD.commit();
System.out.println(
"
**************Test Use Bean : delete**************
"
);
seDelete.close();
}
乐观?
* T2oo.hbn.xml <class> +> optimistic-lock="version"
* id下面 +> <version name="version" type="integer" column="version" />
* +---------+---------+------+
* | Field | Type | Null |
* +---------+---------+------+
* | id | int(11) | |
* | avg | int(11) | |
* | aid | int(11) | YES |
* | version | int(11) | YES |
* +---------+---------+------+
* 注意Q要在数据库中多加一列?br /> * mysql> alter table T2OO add version int;
*/
public
void
testOpLock()
throws
Exception{
//d试数据
Session session
=
sessionFactory.openSession();
Transaction trI
=
session.beginTransaction();
Connection conn
=
session.connection();
T2oo t2oo
=
new
T2oo();
T1oo t1oo
=
new
T1oo(
"
t1ooOpLock
"
);
t1oo.setT2ooSet(
new
HashSet());
t2oo.setAvg(
new
Integer(
23
));
t2oo.setT1oo(t1oo);
t1oo.getT2ooSet().add(t2oo);
session.save(t2oo);
trI.commit();
session.clear();
session.close();
//q发模拟
Session se1
=
sessionFactory.openSession();
Session se2
=
sessionFactory.openSession();
Transaction tr1
=
se1.beginTransaction();
Transaction tr2
=
se2.beginTransaction();
T1oo obj1
=
(T1oo)se1.load(T1oo.
class
,
new
Integer(
1
));
T1oo obj2
=
(T1oo)se2.load(T1oo.
class
,
new
Integer(
1
));
((T2oo)obj1.getT2ooSet().iterator().next()).setAvg(
new
Integer(
9
));
((T2oo)obj2.getT2ooSet().iterator().next()).setAvg(
new
Integer(
10
));
tr1.commit();
try
{
tr2.commit();
}
catch
(Exception e) {
se2.clear();
tr2.commit();
//
tr2报错
}
finally
{
se1.close();
se2.close();
}
//试数据删除
Session dele
=
sessionFactory.openSession();
Transaction tr
=
dele.beginTransaction();
dele.delete(obj1);
tr.commit();
dele.close();
HibernateSessionFactory.closeSession();
}
]]>
1.表属?:T1oo->id,name
T2oo->id,avg,aid(
外键
),version
2.代码q程是:Save->t1oo对象(T1oo 外键 T2oo)
T1oo t1oo = new T1oo();
t1oo.setName("xx");
t1oo.setT2ooSet(new HashSet());
T2oo t2oo2 = new T2oo(24);
//t2oo2.setT1oo(t1oo); (在下面的本用例表中的W?属?)
t1oo.getT2ooSet().add(t2oo2);
(在下面的本用例表中的W?属?)
session.save(t1oo);
3.本例表用:
T1oo.hbm.xml ->
<set name="t2ooSet" inverse="true" cascade = "all" >
(在下面的本用例表中的W?Q?属?)
<key column="aid"/>
<one-to-many class="T2oo"/>
</set>
T2oo.hbm.xml ->
<many-to-one name="t1oo" column="aid" class="T1oo" cascade="all" />
(在下面的本用例表中的W?Q?属?)
l合上面说明得表为:
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | all | | |
+-------+-------+-------+ true | false |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
4.执行
Hibernate语句
Q?/b>
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
5.l果为:
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 2 | 24 | NULL | 0 | //主要是?aid属?/b>
+----+-----+------+---------+
1 row in set (0.00 sec)
mysql> select * from t1oo; //
因ؓ
T1ooL可以 Save 下面׃再提?/font>
+----+------+
| id | name |
+----+------+
| 2 | xx |
+----+------+
1 row in set (0.00 sec)
可改:
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | 可改4 | 可改2 | | |
+-------+-------+-------+ | 可改1 |
| t2oo | | 可改3 | | |
+-------+-------+-------+----------+----------+
L:
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | all | | |
+-------+-------+-------+ true | true |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | all | | |
+-------+-------+-------+ true | false |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | NULL| 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | | | |
+-------+-------+-------+ true | true |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | | | |
+-------+-------+-------+ true | false |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | all | | |
+-------+-------+-------+ true | true |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | | | |
+-------+-------+-------+ true | true |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | all | | |
+-------+-------+-------+ true | false |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | NULL | 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
? ? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | true | | | |
+-------+-------+-------+ true | false |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | all | | |
+-------+-------+-------+ true | true |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
Hibernate: update t2oo set aid=? where id=?
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.02 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | all | | |
+-------+-------+-------+ true | false |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
Hibernate: update t2oo set aid=? where id=?
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | | | |
+-------+-------+-------+ true | true |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: update t2oo set aid=? where id=?
Empty set (0.00 sec)
? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | all | | |
+-------+-------+-------+ true | true |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
Hibernate: update t2oo set aid=? where id=?
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.00 sec)
? ? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | | | |
+-------+-------+-------+ true | true |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: update t2oo set aid=? where id=?
Empty set (0.00 sec)
? ? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | | | |
+-------+-------+-------+ true | false |
| t2oo | | all | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: update t2oo set aid=? where id=?
Empty set (0.00 sec)
? ? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | all | | |
+-------+-------+-------+ true | false |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?)
Hibernate: update t2oo set aid=? where id=?
mysql> select * from t2oo;
+----+-----+------+---------+
| id | avg | aid | version |
+----+-----+------+---------+
| 1 | 24 | 1 | 0 |
+----+-----+------+---------+
1 row in set (0.02 sec)
? ? ? ?
+-------+-------+-------+----------+----------+
|hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo|
+-------+-------+-------+----------+----------+
| t1oo | false | | | |
+-------+-------+-------+ true | false |
| t2oo | | | | |
+-------+-------+-------+----------+----------+
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: update t2oo set aid=? where id=?
Empty set (0.00 sec)
]]>
* Table -> T1oo(id,name)
* Table -> T2oo(id,avg,aid)
* 外键 T1oo.id->T2oo.aid
* Session.createQuery("delete T1oo") -> Query.executeUpdate()
*/
public
void
testExecuteUpdate(){
System.out.println(
"
\r\n\r\n********************ExecuteUpdate************************
"
);
T1oo t1oo
=
new
T1oo();
t1oo.setName(
"
liukaiyi
"
);
HibernateSessionFactory.closeSession();
Session session
=
HibernateSessionFactory.currentSession();
Transaction tr1
=
session.beginTransaction();
//
t1 成ؓ 持久状态 一U缓存中 加蝲
session.saveOrUpdate(t1oo);
//
直接一条语句删除T1ooQ缓存无法同?br />
//
一U缓存中q有 t1
Query qu
=
session.createQuery(
"
delete T1oo
"
);
try
{
qu.executeUpdate();
}
catch
(Exception e) {
System.out.println(
"
//err: 有联 单使用 delete T1oo q要delete T2oo.aid = T1oo.id//
"
);
List list
=
session.createQuery(
"
from T1oo
"
).list();
for
(Iterator it
=
list.iterator();it.hasNext();){
Query t2qu
=
session.createQuery(
"
delete T2oo where aid=:id
"
);
t2qu.setInteger(
"
id
"
, ((T1oo)it.next()).getId().intValue());
t2qu.executeUpdate();
}
qu.executeUpdate();
}
tr1.commit();
Transaction tr2
=
session.beginTransaction();
//
q直接通过一U缓存中加蝲t2Q但DB中以没有此条数据
t1oo
=
(T1oo)session.load(T1oo.
class
,t1oo.getId());
t1oo.setName(
"
google
"
);
try
{
tr2.commit();
}
catch
(Exception e) {
System.out.println(
"
//err: update(t1oo)->DB 中数据库中没有 t1oo //
"
);
}
System.out.println(
"
一U缓存清I前
"
+
session.get(T1oo.
class
,t1oo.getId()) );
session.evict(t1oo);
System.out.println(
"
一U缓存清I后
"
+
session.get(T1oo.
class
,t1oo.getId()) );
//
不把t1oo id 为空Q否则当在saveOrUpdate时候就会以为是游离态 update?/span>
t1oo.setId(
null
);
//
id=null insert 调用
session.saveOrUpdate(t1oo);
tr2.commit();
Transaction tr3
=
session.beginTransaction();
session.delete(t1oo);
tr3.commit();
session.close();
HibernateSessionFactory.closeSession();
}
********************ExecuteUpdate************************
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: delete from t1oo
//err: 有?单?delete T1oo q要delete T2oo.aid = T1oo.id//
Hibernate: select t1oo0_.id as id, t1oo0_.name as name0_ from t1oo t1oo0_
Hibernate: delete from t2oo where aid=?
Hibernate: delete from t2oo where aid=?
Hibernate: delete from t2oo where aid=?
Hibernate: delete from t1oo
Hibernate: update t1oo set name=? where id=?
//err: update(t1oo)->DB 中数据库中没?t1oo //
一U缓存清I前 hbn.bean.T1oo@287
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
一U缓存清I后 null
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: delete from t1oo where id=?
Get Load 区别 Q?br />
* Table -> T1oo(id,name)
* 1.如果未能发现W合条g的记录,getҎq回nullQ而loadҎ会抛出异?br /> * 2.LoadҎ可返回实体的代理cd例,而getҎ永远直接q回实体cR?br /> * 3.loadҎ可以充分利用内部~存和二U缓存中的现有数据,而getҎ则仅仅在内部~存中进行数据查找,
* 如没有发现对应数据,越q二U缓存,直接调用SQL完成数据d。?br /> */
public void testGetLoad() throws Exception {
System.out.println("\r\n\r\n********************Get<>Load************************");
Session session = HibernateSessionFactory.currentSession();
// 数据准备
T1oo t1oo = new T1oo();
t1oo.setName("liu");
Transaction t1 = session.beginTransaction();
session.saveOrUpdate(t1oo);
// Z么这会错Q?br /> //session.evict(t1oo);
//session.flush();
t1.commit();
session.evict(t1oo);
Transaction t2 = session.beginTransaction();
System.out.println("一U缓存是否有t1oo(load)->"+session.contains(t1oo));
//q时候t1oo为 CGlib生成的代理类
t1oo = (T1oo)session.load(T1oo.class,t1oo.getId());
System.out.println(" 延迟加蝲出现Qselect.. t1oo0_.id=? 表的其他属性加q?/span>");
t1oo.setName("load list");
//后在 update
t2.commit();
session.evict(t1oo);
Transaction t3 = session.beginTransaction();
System.out.println("一U缓存是否有t1oo(get)->"+session.contains(t1oo));
//q时候t1oo为 CGlib生成的代理类
t1oo = (T1oo)session.get(T1oo.class,t1oo.getId());
System.out.println(" 没有延迟加蝲出现");
t1oo.setName("get list");
//后在 update
t3.commit();
session.evict(t1oo);
Transaction tr3 = session.beginTransaction();
session.delete(t1oo);
tr3.commit();
session.close();
HibernateSessionFactory.closeSession();
}
********************Get<>Load************************
Hibernate: insert into t1oo (name, id) values (?, ?)
一U缓存是否有t1oo(load)->false
延迟加蝲出现Qselect.. t1oo0_.id=? 表的其他属性加?
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
Hibernate: update t1oo set name=? where id=?
一U缓存是否有t1oo(get)->false
Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=?
没有延迟加蝲出现
Hibernate: update t1oo set name=? where id=?
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=?
Hibernate: delete from t1oo where id=?
Set 集合的识?/font>Q?br />
* Table -> T2oo(id,avg,aid)
* 外键 T1oo.id->T2oo.aid
* T1oo <set name="t2ooSet" inverse="false" cascade = "all" >
* T2oo <many-to-one name="t1oo" column="aid" class="T1oo" />
* cascade='insert' 是一定要?br /> * 当 T1oo没有 inverse="true" d权的时候,要双关?br /> * t1oo.getT2ooSet().add(t2oo1);
* t1oo.getT2ooSet().add(t2oo2);
* t2oo1.setT1oo(t1oo);
* t2oo2.setT1oo(t1oo);
* 要不后sql为:
* Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
* Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
* +----+-----+------+
* | id | avg | aid |
* +----+-----+------+
* | 1 | 24 | NULL |
* | 2 | 23 | NULL |
* +----+-----+------+
* 当 T1oo有 inverse="false"d权的时?br /> * t1oo.getT2ooSet().add(t2oo1);
* t1oo.getT2ooSet().add(t2oo2);
* Sql语句为:
* Hibernate: insert into t1oo (name, id) values (?, ?)
* Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
* Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
* Hibernate: update t2oo set aid=? where id=?
* Hibernate: update t2oo set aid=? where id=?
* | 3 | 24 | 12 |
* | 4 | 23 | 12 |
* +----+-----+------+
*/
public void testSet(){
System.out.println("\r\n\r\n********************Set************************");
T1oo t1oo = new T1oo();
t1oo.setName("list");
T2oo t2oo1 = new T2oo(); t2oo1.setAvg(new Integer(23));
T2oo t2oo2 = new T2oo(); t2oo2.setAvg(new Integer(24));
Session session = HibernateSessionFactory.currentSession();
Transaction tr1 = session.beginTransaction();
session.save(t1oo);
t1oo = (T1oo) session.load(T1oo.class,t1oo.getId());
t1oo.setT2ooSet(new HashSet()) ;
t1oo.getT2ooSet().add(t2oo1);
t1oo.getT2ooSet().add(t2oo2);
System.out.println( t1oo.getT2ooSet().size()+"" );
tr1.commit();
System.out.println();
T2oo t2oo3 = new T2oo(); t2oo3.setAvg(new Integer(25));
T1oo t1oo2 = new T1oo(); t1oo2.setName("mz");
t2oo3.setT1oo(t1oo2);
Transaction tr2 = session.beginTransaction();
session.save(t2oo3);
try {
tr2.commit();
} catch (Exception e) {
System.out.println("//err: 没有d权 cascade = 'all' 不可以联save t1oo //");
}
session.close();
HibernateSessionFactory.closeSession();
}
l果是:
********************Set************************
2
Hibernate: insert into t1oo (name, id) values (?, ?)
Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?)
Hibernate: update t2oo set aid=? where id=?
Hibernate: update t2oo set aid=? where id=?
//err: 没有d?cascade = 'all' 不可以联save t1oo //
]]>
public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0) );
public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection( new ArrayList(0) );
public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) );
private CollectionHelper() {}
}
悟: 从上面看出是一个非常好的?适配?
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<T>(c);
}
//2.内部c?/font>也? Collection
static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
private static final long serialVersionUID = 1820017752578914078L;
final Collection<? extends E> c;
//3.很好适配 Collection 通过他把 add remove {功?装
UnmodifiableCollection(Collection<? extends E> c) {
if (c==null)
throw new NullPointerException();
this.c = c;
}
...............
2.大量使用内部cL??如:
////////////////////////////////////////////////
Mappings?br /> static final class PropertyReference implements Serializable {
String referencedClass;
String propertyName;
boolean unique;
}
//感觉是可以更好的代码~写
]]>
1Q查询条仉过 Criteria.add d Expression 用于描述条g
Expression.( and or like in le lt ..... )
参见Q?Criteria查询
2Qcriteria.setFirstResult(100);
criteria.setMaxResults(20); //索范?br /> criteria.addOrder(Order.asc("name")); //排序
.add( Expression.sql("lower($alias.name) like lower(?)", "Fritz%", Hibernate.STRING) //直接嵌入SQL
3Q?/font>Cat cat = new Cat();
....
List results = session.createCriteria(Cat.class).add( Example.create(cat) ).list(); //Ҏ对象查询
3。HQL 完全面向对象的,具备l承、多态和兌{特性?br /> 1Q参见: HQL
2Q内q接Qinner join
左外q接Qleft outer join
叛_q接Qright outer join
http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html
代表性的语句
<set name="fkSet" inverse="true">
<key column="id"/>
<one-to-many class="Fk"/>
</set>
SQL
alter table fk add constraint FK_hf foreign key(id) references hql(id)
mysql> select * from hql;
+----+----------+
| id | name |
+----+----------+
| 0 | liukaiyi |
| 1 | heha |
+----+----------+
2 rows in set (0.00 sec)
mysql> select * from fk;
+----+------+
| id | name |
+----+------+
| 0 | yy |
| 1 | xx |
+----+------+
2 rows in set (0.00 sec)
//单的 l果Q?2 liukaiyi:heha
" from Hql h , Fk f" +
" where h.id = f.id" );
List list = qu.list() ;
tr.commit();
System.out.println( list.size() );
System.out.println( list.get(0)+":"+list.get(1) );
//l出对象 l果 : heha
((Hql)list.get(0)).getName() ;
//l出Object l果Qheha xx
List list = qu.list() ;
tr.commit();
System.out.println(list.size());
Object[] objs = (Object[]) list.get(0) ;
System.out.println( objs[0] +":"+objs[1] );
//l出 Map heha xx
Query qu = se.createQuery("select new map( h.name as hn,f.name as fn)from Hql h join h.fkSet f where f.name='xx'");
List list = qu.list() ;
tr.commit();
System.out.println(list.size());
Map map = ((Map)list.get(0));
System.out.println( map.get("hn") );
}
//报表语句 l果: 1
" where h.name='heha' and h.id=f.id " +
" group by h.name ");
List list = qu.list() ;
tr.commit();
System.out.println( list.get(0) );
//集合?l果 liukaiyi:heha
//元素?elements?tt class="literal">indices 函数) 可以使用 any, some, all, exists, in
//EG: from Player p where 3 > all elements(p.scores)
| id | name |
+----+----------+
| 0 | liukaiyi |
| 1 | heha |
| 3 | oo |
+----+----------+
Query qu = se.createQuery("select h.name " +
" from Hql h" +
" where h.id in elements(h.fkSet.id) " );
List list = qu.list() ;
tr.commit();
System.out.println( list.get(0)+":"+list.get(1) );
//使用 javaBean l定
q.setProperties(fooBean); // fooBean包含ҎgetName()与getSize()
List foos = q.list();
]]>
1.Criteria ?or
<set name="emails" table="email">//email?/font> ?2?id address
<key column="id"/> //email表的主键 也是主表的主?/font>
<element type="java.lang.String" column="address"/>
</set>
.java private Set emails; //存和外键?/font>
2)List ?.xml
<list name="items" table="item">
<key column="id"/> //?/font>item表的 idINT(11) NOT NULL,
<index column="position"/> //?position INT(11) NOT NULL,
<element type="java.lang.String" column="name"/>//?/font>name VARCHAR(100) NOT NULL default ''
</list>
。。。。?br />3. 列ؓ对象
<set name="emails" table="email">
<key column="id"/>
<composite-element class="onlyfun.caterpillar.MailAddress">
<property name="address" column="address"/> //调用 getAddress()
</composite-element>
</set>