上一篇文章写了如何使用spring的注解,这一篇记录一下和hibernate简单配合。
1.使用各种mysql客户端或直接命令行执行如下脚本:
create database if not exists `test`;
USE `test`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.既然是ORM当然需要Model了
package com.isa.demo2.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.apache.commons.lang.builder.ToStringBuilder;
@Entity
@Table(name = "user")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = -9029863029696113906L;
private long id;
private String name;
@Id
@Column(name = "ID", unique = true, nullable = false, scale = 0)
@GeneratedValue(strategy=GenerationType.IDENTITY)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(name = "NAME", unique = true, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
3.关于需不需要dao层的问题,看大家的习惯吧,作为一个demo,简单明了即可。这里使用了以前的一个项目的结构。
package com.isa.demo2.service;
import java.util.List;
import com.isa.demo2.domain.User;
public interface UserService {
List<User> getAllUsers();
User getUserById(long id);
}
4.接口的实现类
package com.isa.demo2.service;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.isa.demo2.domain.User;
public class UserServiceImpl implements UserService {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<User> getAllUsers() {
Session session = sessionFactory.getCurrentSession();
String hql = "from User";
List<User> list = session.createQuery(hql).list();
return list;
}
@Override
public User getUserById(long id) {
Session session = sessionFactory.getCurrentSession();
User user = (User) session.get(User.class, id);
return user;
}
}
5.配置文件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"
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"
default-autowire="byName" default-lazy-init="true">
<!-- 支持 @Transactional 标记 -->
<tx:annotation-driven/>
<!-- 支持 @AspectJ 标记-->
<aop:aspectj-autoproxy/>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.isa.demo2.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<bean id="userService" class="com.isa.demo2.service.UserServiceImpl"></bean>
</beans>
第二个配置文件applicationContext-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-autowire="byName" default-lazy-init="true">
<!-- 数据源定义,使用dbcp 连接池 -->
<!-- 数据源配置,使用应用内的DBCP数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- Connection Info -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!-- Connection Pooling Info -->
<property name="initialSize" value="5" />
<property name="maxActive" value="100" />
<property name="maxIdle" value="30" />
<property name="maxWait" value="1000" />
<property name="poolPreparedStatements" value="false" />
<property name="defaultAutoCommit" value="false" />
</bean>
<!--Hibernate SessionFatory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.isa.demo2.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property>
</bean>
<!--Hibernate TransactionManager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
6.简单测试类
package com.isa.demo2.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.isa.demo2.service.UserService;
public class Demo2Test {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "demo2/*.xml" });
UserService service = (UserService)context.getBean("userService");
System.out.println(service.getUserById(1L).toString());
}
}
7.说明:这个demo来源于我刚毕业的时候做的一个项目,这是第一次接触spring和hibernate,那个项目的架构看起来蛮怪异,C#+hessian+hibernate+spring+Oracle,呵呵,为什么是C#呢?而且还是客户端程序,看到hessian就知道了。一些技术真的不用就忘记了,在这一段没有使用hibernate和spring的时间更新和添加了很多特性,现在重新看一下也算是与时俱进。再唠叨一下,技术和语言是永无止境的,但是学习的技巧和经验是需要归纳总结才能进步的。