Hibernate学习记录3 Hibernate 配置多数据源
2017-04-15 15:38
435 查看
实验环境
Spring3.1.1Hibernate 4.1.4
Jersey
示例中只使用了一个secondFactory_second。另一个sessionFactory代码不是处理核心,这里未贴出。
model定义
@Message public class User implements java.io.Serializable { // Fields private String userUnid; private String userLoginName; // Constructors /** default constructor */ public User() { } /** minimal constructor */ public User(String userUnid) { this.userUnid = userUnid; } /** full constructor */ public User(String userUnid, String userLoginName) { this.userUnid = userUnid; this.userLoginName = userLoginName; } // Property accessors public String getUserUnid() { return this.userUnid; } public void setUserUnid(String userUnid) { this.userUnid = userUnid; } public String getUserLoginName() { return this.userLoginName; } public void setUserLoginName(String userLoginName) { this.userLoginName = userLoginName; } }
dao
import java.util.List; import org.hibernate.LockOptions; import org.hibernate.Query; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.transaction.annotation.Transactional; import com.cn.hightech.hb.BaseHibernateDAO; @Transactional public class UserDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory .getLogger(UserDAO.class); public static final String USER_LOGIN_NAME = "userLoginName"; public void save(User transientInstance) { log.debug("saving User instance"); try { getCurrentSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(User persistentInstance) { log.debug("deleting User instance"); try { getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public User findById(java.lang.String id) { log.debug("getting User instance with id: " + id); try { User instance = (User) getCurrentSession().get( "com.cn.hightech.entity.gx.User", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(User instance) { log.debug("finding User instance by example"); try { List results = getCurrentSession() .createCriteria("com.cn.hightech.entity.gx.User") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding User instance with property: " + propertyName + ", value: " + value); try { String queryString = "from User as model where model." + propertyName + "= ?"; Query queryObject = getCurrentSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByUserLoginName(Object userLoginName) { return findByProperty(USER_LOGIN_NAME, userLoginName); } public List findAll() { log.debug("finding all User instances"); try { String queryString = "from User"; Query queryObject = getCurrentSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public User merge(User detachedInstance) { log.debug("merging User instance"); try { User result = (User) getCurrentSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(User instance) { log.debug("attaching dirty User instance"); try { getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(User instance) { log.debug("attaching clean User instance"); try { getCurrentSession().buildLockRequest(LockOptions.NONE).lock( instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } @SuppressWarnings("unchecked") public List<User> findByPage(int page,int limit,String where,String order) { log.debug("finding page User instances"); try { String queryString = "from User"; if(!(where.equals("") || where.equals("''")))queryString = queryString+" WHERE "+where; if(!(order.equals(""))) queryString=queryString+ " ORDER BY " +order; Query queryObject = getCurrentSession().createQuery(queryString); queryObject.setMaxResults(limit); queryObject.setFirstResult((page-1)*limit); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public int count(String where){ log.debug("counting User instances"); try { String queryString = "select count(*) from User table"; if(!where.equals(""))queryString = queryString+" WHERE "+where; Long count = (Long)getCurrentSession().createQuery(queryString).uniqueResult(); return count.intValue(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public static UserDAO getFromApplicationContext(ApplicationContext ctx) { UserDAO m= (UserDAO) ctx.getBean("UserDAO"); return m; } }
BaseHibernateDAO
public class BaseHibernateDAO implements IBaseHibernateDAO { @Override public Session getSession() { //return HibernateessFactory.getSession(); return secondFactory_second.getCurrentSession(); } private secondFactory secondFactory; public void setsecondFactory(secondFactory secondFactory) { this.secondFactory = secondFactory; } public Session getCurrentSession() { return secondFactory.getCurrentSession(); } protected void initDao() { // do nothing } /** * 把某个对象变成游离 防止误改属性 * @param m */ public void evict(Object m){ getSession().evict(m);; } public void flush(){ getSession().flush(); } public void clear(){ getSession().clear(); } public void commit(){ getSession().getTransaction().commit(); } public void beginTrasaction(){ getSession().beginTransaction(); } public void rollback(){ getSession().getTransaction().rollback(); } }
HibernateessFactory
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.secondFactory; public class HibernateSessionFactory { private static secondFactory secondFactory; private HibernateSessionFactory() { } public static Session getSession() throws HibernateException { return sessionFactory_second.getCurrentSession(); } public static void closeSession() throws HibernateException { if (sessionFactory_second.getCurrentSession() != null) { sessionFactory_second.getCurrentSession().close(); } } public SessionFactory getSessionFactory() { return sessionFactory_second; } public void setSessionFactory(SessionFactory sf){ sessionFactory_second = sf; } }
IBaseHibernateDAO
import org.hibernate.Session; /** * Data accsecond interface for domain model * @author MyEclipse Persistence Tools */ public interface IBaseHibernateDAO { public Session getSession(); }
hbm.xml
<hibernate-mapping> <class name="com.cn.hightech.entity.gx.User" table="_USER" schema="WAS"> <id name="userUnid" type="java.lang.String"> <column name="USER_UNID" length="32" /> <generator class="assigned" /> </id> <property name="userLoginName" type="java.lang.String"> <column name="USER_LOGIN_NAME" length="100" /> </property> </class> </hibernate-mapping>
applicationContext.xml
<!-- gx --> <bean id="dataSource_second" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="oracle.jdbc.OracleDriver"></property> <property name="jdbcUrl" value="jdbc:oracle:thin:@112.29.170.10:1521:gx"></property> <property name="user" value="gx"></property> <property name="password" value="feFG33$$523"></property> <property name="maxIdleTime" value="60"></property> <property name="maxPoolSize" value="20"></property> <property name="minPoolSize" value="10"></property> <property name="acquireRetryDelay" value="1000"></property> <property name="acquireRetryAttempts" value="60"></property> <property name="breakAfterAcquireFailure" value="false"></property> </bean> <bean id="secondFactory_second" class="org.springframework.orm.hibernate4.LocalsecondFactoryBean"> <property name="dataSource"><ref bean="dataSource_second" /></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="current_Session_context_class">thread</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.jdbc.fetch_size">50</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="mappingResources"> <list> <value>com/cn/hightech/entity/gx/Dept.hbm.xml</value> <value>com/cn/hightech/entity/gx/User.hbm.xml</value> </list> </property> </bean> <bean id="hibernatesecondFactory_second" class="com.cn.hightech.hb.HibernatesecondFactory"> <property name="secondFactory"><ref bean="secondFactory_second" /></property> </bean> <bean id="transactionManager_second" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="secondFactory" ref="secondFactory_second" /> </bean> <tx:annotation-driven transaction-manager="transactionManager_second" proxy-target-class="true"/> <bean id="UserDAO" class="com.cn.hightech.entity.gx.UserDAO"> <property name="secondFactory"> <ref bean="sessionFactory_second" /> </property> </bean>
controller
/** * 下面@Transactional 和 @Service @Provider注解都需要 **/ @Service @Provider @Path("/User/") @Transactional("transactionManager_second") public class UserController extends BaseController{ private static final long serialVersionUID = 1L; @Context private HttpServletRequest request; @Context private ApplicationContext ctx; public UserController(){ } public UserController(HttpServletRequest request1){ request=request1; } @Transactional("transactionManager_second") @GET @Path("/Query/") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public User Query(@QueryParam("USER_UNID") String USER_UNID) throws IOException{ //登陆验证 User loginUser=QueryFromCache(); if(loginUser==null)return null; return UserDAO.getFromApplicationContext(ctx).findById(USER_UNID); } }
一个问题处理
No session found in current thread
如果Controller使用的Transactional不是默认 ,在controller的方法上要加注解:
@Transactional("transactionManager_gxwas")
相关文章推荐
- hibernate二级缓存配置学习记录
- Hibernate学习记录5 配置C3P0
- 记录hibernate 3学习过程中的报错(未完成)
- Hibernate学习手记——SQL server MiddleGen配置问题
- 传智播客hibernate学习,开发环境配置
- Hibernate学习小结(一)――Hibernate配置
- hibernate的QBC查询学习记录
- 记录hibernate 3学习过程中的报错(未完成)
- Hibernate学习笔记:配置hibernate日志
- ASP.net中的AJAX学习记录六 无刷新的数据编辑(GridView和DetailsView结合实例)
- ASP.net中的AJAX学习记录六 无刷新的数据编辑(GridView和DetailsView结合实例)
- Hibernate学习笔记2--------------------一对多、多对一简单配置
- MOSS Search学习记录(二):配置爬网并尝试一个简单的搜索
- Java学习之hibernate配置要点详谈
- GDI+ 学习记录(28): 图像颜色的数据格式 - PixelFormat
- hibernate 配置文件生成数据库
- Java学习之hibernate配置要点详谈
- MOSS Search学习记录(三):配置搜索范围
- 数据持久化Hibernate的标准数据库连接池配置(转)
- 传智播客oa学习,配置struts+ hibernate + jbpm