以上是配置文件部分,接下来来看具体代码。
三、通用DAO层Hibernate4实现
为了减少各模块实现的代码量,实际工作时都会有通用DAO层实现,以下是部分核心代码:
java代码: 查看复制到剪贴板打印
public abstract class BaseHibernateDao
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseHibernateDao.class);
private final Class
private final String HQL_LIST_ALL;
private final String HQL_COUNT_ALL;
private final String HQL_OPTIMIZE_PRE_LIST_ALL;
private final String HQL_OPTIMIZE_NEXT_LIST_ALL;
private String pkName = null;
@SuppressWarnings("unchecked")
public BaseHibernateDao() {
this.entityClass = (Class
Field[] fields = this.entityClass.getDeclaredFields();
for(Field f : fields) {
if(f.isAnnotationPresent(Id.class)) {
this.pkName = f.getName();
}
}
Assert.notNull(pkName);
//TODO @Entity name not null
HQL_LIST_ALL = "from " + this.entityClass.getSimpleName() + " order by " + pkName + " desc";
HQL_OPTIMIZE_PRE_LIST_ALL = "from " + this.entityClass.getSimpleName() + " where " + pkName + " > order by " + pkName + " asc";
HQL_OPTIMIZE_NEXT_LIST_ALL = "from " + this.entityClass.getSimpleName() + " where " + pkName + " < order by " + pkName + " desc";
HQL_COUNT_ALL = " select count(*) from " + this.entityClass.getSimpleName();
}
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
//事务必须是开启的,否则获取不到
return sessionFactory.getCurrentSession();
}
……
}
public abstract class BaseHibernateDao
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseHibernateDao.class);
private final Class
private final String HQL_LIST_ALL;
private final String HQL_COUNT_ALL;
private final String HQL_OPTIMIZE_PRE_LIST_ALL;
private final String HQL_OPTIMIZE_NEXT_LIST_ALL;
private String pkName = null;
@SuppressWarnings("unchecked")
public BaseHibernateDao() {
this.entityClass = (Class
Field[] fields = this.entityClass.getDeclaredFields();
for(Field f : fields) {
if(f.isAnnotationPresent(Id.class)) {
this.pkName = f.getName();
}
}
Assert.notNull(pkName);
//TODO @Entity name not null
HQL_LIST_ALL = "from " + this.entityClass.getSimpleName() + " order by " + pkName + " desc";
HQL_OPTIMIZE_PRE_LIST_ALL = "from " + this.entityClass.getSimpleName() + " where " + pkName + " > order by " + pkName + " asc";
HQL_OPTIMIZE_NEXT_LIST_ALL = "from " + this.entityClass.getSimpleName() + " where " + pkName + " < order by " + pkName + " desc";
HQL_COUNT_ALL = " select count(*) from " + this.entityClass.getSimpleName();
}
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
//事务必须是开启的,否则获取不到www.2cto.com
return sessionFactory.getCurrentSession();
}
……
}
Spring3.1集成Hibernate4不再需要HibernateDaoSupport和HibernateTemplate了,直接使用原生API即可。
四、通用Service层代码 此处省略,看源代码,有了通用代码后CURD就不用再写了。
java代码: 查看复制到剪贴板打印
@Service("UserService")
public class UserServiceImpl extends BaseService
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
private UserDao userDao;
@Autowired
@Qualifier("UserDao")
@Override
public void setBaseDao(IBaseDao
this.baseDao = userDao;
this.userDao = (UserDao) userDao;
}
@Override
public Page
return PageUtil.getPage(userDao.countQuery(command) ,pn, userDao.query(pn, pageSize, command), pageSize);
}
}
@Service("UserService")
public class UserServiceImpl extends BaseService
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
private UserDao userDao;
@Autowired
@Qualifier("UserDao")
@Override
public void setBaseDao(IBaseDao
this.baseDao = userDao;
this.userDao = (UserDao) userDao;
}
@Override
public Page
return PageUtil.getPage(userDao.countQuery(command) ,pn, userDao.query(pn, pageSize, command), pageSize);
}
}
五、表现层 Controller实现
采用SpringMVC支持的REST风格实现,具体看代码,此处我们使用了java Validator框架 来进行 表现层数据验证
在Model实现上加验证注解
java代码: 查看复制到剪贴板打印
@Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
private String username;
@NotEmpty(message = "{email.illegal}")
@Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
private String email;
@Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
private String password;
@DateFormat( message="{register.date.error}")//自定义的验证器
private Date registerDate;
@Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{username.illegal}") //java validator验证(用户名字母数字组成,长度为5-10)
private String username;
@NotEmpty(message = "{email.illegal}")
@Email(message = "{email.illegal}") //错误消息会自动到MessageSource中查找
private String email;
@Pattern(regexp = "[A-Za-z0-9]{5,20}", message = "{password.illegal}")
private String password;
@DateFormat( message="{register.date.error}")//自定义的验证器
private Date registerDate;
在Controller中相应方法的需要验证的参数上加@Valid即可
java代码: 查看复制到剪贴板打印
@RequestMapping(value = "/user/add", method = {RequestMethod.POST})
public String add(Model model, @ModelAttribute("command") @Valid UserModel command, BindingResult result)
@RequestMapping(value = "/user/add", method = {RequestMethod.POST})
public String add(Model model, @ModelAttribute("command") @Valid UserModel command, BindingResult result)
六、Spring集成测试
使用Spring集成测试能很方便的进行Bean的测试,而且使用@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)能自动回滚事务,清理测试前后状态。
java代码: 查看复制到剪贴板打印
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-config.xml"})
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)
public class UserServiceTest {
AtomicInteger counter = new AtomicInteger();
@Autowired
private UserService userService;
……
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-config.xml"})
@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)
public class UserServiceTest {
AtomicInteger counter = new AtomicInteger();
@Autowired
private UserService userService;
……
}
其他部分请直接看源码,欢迎大家讨论。
补充spring3.1.1源代码分析当 传播行为为 Support时报 org.hibernate.HibernateException: No Session found for current thread 异常:
spring3.1开始 不提供(没有这个东西了)Hibernate4的 DaoSupport和Template,,而是直接使用原生的Hibernate4 API
如在 Hibernate3中 HibernateTemplate中有如下代码
Java代码
protected Session getSession() {
if (isAlwaysUseNewSession()) {
return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
}
else if (isAllowCreate()) {//默认是true,也就是即使你的传播行为是Supports也一定会有session存在的
return SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
}
else if (SessionFactoryUtils.hasTransactionalSession(getSessionFactory())) {
return SessionFactoryUtils.getSession(getSessionFactory(), false);
}
else {
try {
return getSessionFactory().getCurrentSession();
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
}
}
}
但我们使用的是Hibernate4原生API,使用SpringSessionContext获取session,而这个isAllowCreate选项默认为false
Java代码
/**
* Retrieve the Spring-managed Session for the current thread, if any.
*/
public Session currentSession() throws HibernateException {
try {
return (org.hibernate.classic.Session) SessionFactoryUtils.doGetSession(this.sessionFactory, false);//最后的false即是
}
catch (IllegalStateException ex) {
throw new HibernateException(ex.getMessage());
}
}
SessionFactoryUtils类
Java代码
public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate)
throws HibernateException, IllegalStateException {
return doGetSession(sessionFactory, null, null, allowCreate);
}
可否认为这是集成Hibernate4的bug,或者采用OpenSessionInView模式解决或使用Required传播行为。
摘自 zhang的笔记