浏览 6086 次
锁定老帖子 主题:spring注解那些事
精华帖 (0) :: 良好帖 (1) :: 新手帖 (12) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-06-24
最后修改:2009-06-24
配置文件:applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <!--*******************Hibernate数据库持久层配置文件***********************--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 --> <context:component-scan base-package="com.itdcl.agcds.webinfo" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <!-- property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />--> <!-- 自动扫描实体 --> <property name="packagesToScan" value="com.itdcl.agcds.webinfo.model*.*" /> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> ${hibernate.dialect} </prop> <prop key="show_sql">${show_sql}</prop> <prop key="format_sql">${format_sql}</prop> <!-- 缓存设置 --> <prop key="cache.use_query_cache"> ${cache.use_query_cache} </prop> <prop key="cache.use_second_level_cache"> ${cache.use_second_level_cache} </prop> <prop key="cache.provider_class"> ${cache.provider_class} </prop> <prop key="c3p0.acquire_increment"> ${c3p0.acquire_increment} </prop> <prop key="c3p0.max_statements"> ${c3p0.max_statements} </prop> <prop key="c3p0.min_size">${c3p0.min_size}</prop> <prop key="c3p0.max_size">${c3p0.max_size}</prop> <prop key="c3p0.timeout">${c3p0.timeout}</prop> <prop key="c3p0.idle_test_period"> ${c3p0.idle_test_period} </prop> </props> </property> </bean> <!-- 使用annotation定义事务 <tx:annotation-driven transaction-manager="transactionManager" />--> <!-- Hibernate TransactionManager --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> 实体类:SysUser.java @Entity @Table(name="SYS_USER") public class SysUser implements java.io.Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="USER_ID") private Integer userId; @Column(name="USER_NAME") private String userName; @Column(name="USER_PWD") private String userPwd; @Column(name="USER_TYPE") private Integer userType; @ManyToMany(cascade={ CascadeType.PERSIST, CascadeType.MERGE },mappedBy="userSet") private Set<SysRole> roleSet = new HashSet<SysRole>(0); public SysUser() { } public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return this.userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public Integer getUserType() { return this.userType; } public void setUserType(Integer userType) { this.userType = userType; } public Set<SysRole> getRoleSet() { return roleSet; } public void setRoleSet(Set<SysRole> roleSet) { this.roleSet = roleSet; } } DAO:HibernateBaseDAO.java public interface HibernateBaseDAO<T, PK extends Serializable> { public List<T> loadAll(); } DAO实现类:HibernateBaseDAOImpl.java @Repository public class HibernateBaseDAOImpl<T, PK extends Serializable> extends HibernateDaoSupport implements HibernateBaseDAO<T, PK> { // 实体类类型(由构造方法自动赋值) private Class<T> entityObject; @Autowired public void setSessionFactoryOverride(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } // 构造方法,根据实例类自动获取实体类类型 @SuppressWarnings("unchecked") public HibernateBaseDAOImpl() { this.entityObject = null; Class<?> calzz = getClass(); Type type = calzz.getGenericSuperclass(); if (type instanceof ParameterizedType) { Type[] param = ((ParameterizedType) type).getActualTypeArguments(); this.entityObject = (Class<T>) param[0]; } } // 构造方法,根据实例类自动获取SessionFactory与实体类类型 public HibernateBaseDAOImpl(SessionFactory sessionFactory, Class<T> entityObject) { super.setSessionFactory(sessionFactory); this.entityObject = entityObject; } // 获取全部实体。 @SuppressWarnings("unchecked") public List<T> loadAll() { logger.info("++++++++++++++++++Hibernate"); return getHibernateTemplate().loadAll(entityObject); } } 业务逻辑接口:IService.java public interface IService<T, PK extends Serializable> { public List<T> findAllList(); } SysUserService.java public interface SysUserService extends IService<SysUser,Long>{} 业务逻辑实现类:BaseService.java @Service @Transactional public class BaseService<T, PK extends Serializable> implements IService<T, PK> { .... } SysUserServiceImpl.java @Service @Transactional public class SysUserServiceImpl extends BaseService<SysUser, Long> implements SysUserService { ... } JUnit测试类:SysUserServiceTest.java @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/applicationContext.xml" }) public class SysUserServiceTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private SysUserService sysUserService; @Test public void testGetSize() { List<SysUser> list = sysUserService.findAllList(); System.out.println("********************"); for(SysUser user:list){ System.out.println(user.getUserName()+"----"+user.getUserPwd()); } System.out.println("********************"); Assert.assertEquals(2, list.size()); } } 跑一下测试用例,控制台打印几条警告信息: WARN 09 六月 24 13:17:28 org.springframework.aop.framework.Cglib2AopProxy.doValidateClass(Cglib2AopProxy.java:256) - Unable to proxy method [public final void org.springframework.orm.hibernate3.support.HibernateDaoSupport.setSessionFactory(org.hibernate.SessionFactory)] because it is final: All calls to this method via a proxy will be routed directly to the proxy. WARN 09 六月 24 13:17:28 org.springframework.aop.framework.Cglib2AopProxy.doValidateClass(Cglib2AopProxy.java:256) - Unable to proxy method [public final org.springframework.orm.hibernate3.HibernateTemplate org.springframework.orm.hibernate3.support.HibernateDaoSupport.getHibernateTemplate()] because it is final: All calls to this method via a proxy will be routed directly to the proxy. WARN 09 六月 24 13:17:28 org.springframework.aop.framework.Cglib2AopProxy.doValidateClass(Cglib2AopProxy.java:256) - Unable to proxy method [public final org.hibernate.SessionFactory org.springframework.orm.hibernate3.support.HibernateDaoSupport.getSessionFactory()] because it is final: All calls to this method via a proxy will be routed directly to the proxy. WARN 09 六月 24 13:17:28 org.springframework.aop.framework.Cglib2AopProxy.doValidateClass(Cglib2AopProxy.java:256) - Unable to proxy method [public final void org.springframework.orm.hibernate3.support.HibernateDaoSupport.setHibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate)] because it is final: All calls to this method via a proxy will be routed directly to the proxy. WARN 09 六月 24 13:17:28 org.springframework.aop.framework.Cglib2AopProxy.doValidateClass(Cglib2AopProxy.java:256) - Unable to proxy method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] because it is final: All calls to this method via a proxy will be routed directly to the proxy. 再强调一下,Sys_User表中有两条数据,但是全部查出来为0.找了许多资料,还是没有结果。那位高人知道,麻烦回个贴,谢谢! 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-06-25
今天终于搞定啦,还是我自己回复,也给遇到同样问题的人一点帮助吧。
数据查不出来,但表中有数据,又没有报错。问题出在那呢,事务上啊。那那个地方与事务有关联呢? # <!-- 使用annotation定义事务 # <tx:annotation-driven transaction-manager="transactionManager" />--> # # <!-- Hibernate TransactionManager --> # <bean id="transactionManager" # class="org.springframework.orm.hibernate3.HibernateTransactionManager"> # <property name="sessionFactory" ref="sessionFactory" /> # </bean> 这样配置没有错啊,走了几遍还是没有结果。结果一想,查询记录需要要事务吗?那好我们就来一个修改用户的测试方法,看看事务正常不啦,结果runnig,又出了下一个问题,not mapped entity SysUser。仔细检查一下配置文件,没有映射实体,那也就是实体自动扫描出题,到网上一起,差不多都这样配置的啊。就是这个差不多,版本不同,就也有点差。改成 com.itdcl.agcds.webinfo.model就OK啦。 还没说完,我不是修改用户信息吗,结果数据库中信息没有变化啊。查了一下Spring API,看看AbstractTransactionalJUnit4SpringContextTests究竟是怎么用的. AbstractTransactionalDataSourceSpringContextTests,它可以保持数据的清洁,操作完之后就回滚。怪不得没有变化呢,那怎么让他变化呢,再看API,在方法上面加一个注解@Rollback(false)就搞定啦。呵呵,不过这样就不能保证数据清洁啦。 |
|
返回顶楼 | |