1.Maven Dependency
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.springjdbc</groupId> <artifactId>springhibernate</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springhibernate</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring-version>3.2.2.RELEASE</spring-version> <aspectj-version>1.7.2</aspectj-version> <commons-dbcp-version>1.4</commons-dbcp-version> <hibernate-version>4.1.11.Final</hibernate-version> <junit-version>4.11</junit-version> <mysql-connector-version>5.1.24</mysql-connector-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj-version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${commons-dbcp-version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate-version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-version}</version> </dependency> </dependencies> </project>
2.Project Directory
3.src/main/resources
schema.sql
drop table if exists t_user ; drop table if exists t_group ; create table t_group ( gid integer not null auto_increment, name varchar(20) not null, constraint group_gid_pk primary key(gid) ); create table t_user ( uid integer not null auto_increment, username varchar(20) not null, password varchar(20) not null, nickname varchar(20) not null, gid integer, constraint user_uid_pk primary key(uid), constraint group_user_gid_fk foreign key(gid) references t_group(gid) );
log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file hibernate.log ### #log4j.appender.file=org.apache.log4j.FileAppender #log4j.appender.file.File=hibernate.log #log4j.appender.file.layout=org.apache.log4j.PatternLayout #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=info #log4j.logger.org.hibernate=debug ### log HQL query parser activity #log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### #log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=debug ### log schema export/update ### #log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log transaction activity #log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
jdbc.properties
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc.username = root jdbc.password = 123456
beans.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <context:annotation-config /> <context:component-scan base-package="org.fool.springhibernate" /> <context:property-placeholder location="classpath:jdbc.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置连接池的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <!-- <property name="maxActive" value="500"/> --> <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 --> <!-- <property name="maxIdle" value="2"/> --> <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 --> <property name="minIdle" value="1" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="20" /> <property name="maxWait" value="1000" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="org.fool.springhibernate.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL5Dialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext </prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <aop:pointcut id="allMethods" expression="execution(* org.fool.springhibernate.dao.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true" /> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> </beans>
4.src/main/java
Group.java
package org.fool.springhibernate.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_group") public class Group { private int id; private String name; @Id @GeneratedValue @Column(name ="gid") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Group [id=" + id + ", name=" + name + "]"; } }
User.java
package org.fool.springhibernate.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "t_user") public class User { private int id; private String username; private String password; private String nickname; private Group group; public User() { } public User(String username, String password, String nickname) { this.username = username; this.password = password; this.nickname = nickname; } @ManyToOne @JoinColumn(name = "gid") public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @Id @GeneratedValue @Column(name = "uid") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", nickname=" + nickname + ", group=" + group + "]"; } }
BaseDAO.java
package org.fool.springhibernate.dao; import java.util.List; public interface BaseDAO<T> { public void add(T t); public void delete(int id); public void update(T t); public T load(int id); public List<T> list(String hql, Object[] args); public List<T> list(String hql, Object arg); public List<T> list(String hql); }
BaseDAOImpl.java
package org.fool.springhibernate.dao; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class BaseDAOImpl<T> implements BaseDAO<T> { @Resource private SessionFactory sessionFactory; /** * 创建一个Class的对象来获取泛型的class */ private Class<T> clz; @SuppressWarnings("unchecked") public Class<T> getClz() { if (clz == null) { // 获取泛型的Class对象 clz = ((Class<T>) (((ParameterizedType) (this.getClass() .getGenericSuperclass())).getActualTypeArguments()[0])); } return clz; } protected Session getSession() { return sessionFactory.getCurrentSession(); } @Override public void add(T t) { this.getSession().save(t); } @Override public void delete(int id) { this.getSession().delete(this.load(id)); } @Override public void update(T t) { this.getSession().update(t); } @SuppressWarnings("unchecked") @Override public T load(int id) { return (T) this.getSession().get(getClz(), id); } @SuppressWarnings("unchecked") @Override public List<T> list(String hql, Object[] args) { Query query = this.getSession().createQuery(hql); if (args != null) { for (int i = 0; i < args.length; i++) { query.setParameter(i, args[i]); } } return query.list(); } @Override public List<T> list(String hql, Object arg) { return this.list(hql, new Object[] { arg }); } @Override public List<T> list(String hql) { return this.list(hql, null); } }
GroupDAO.java
package org.fool.springhibernate.dao; import org.fool.springhibernate.model.Group; public interface GroupDAO extends BaseDAO<Group> { }
GroupDAOImpl.java
package org.fool.springhibernate.dao; import org.fool.springhibernate.model.Group; import org.springframework.stereotype.Repository; @Repository("groupDAO") public class GroupDAOImpl extends BaseDAOImpl<Group> implements GroupDAO { }
UserDAO.java
package org.fool.springhibernate.dao; import org.fool.springhibernate.model.User; public interface UserDAO extends BaseDAO<User> { /** * 添加用户 */ public void add(User user, int gid); /** * 获取某个组中的用户数量 */ public long getGroupUserCount(int gid); /** * 删除组中的用户 */ public void deleteByGroup(int gid); }
UserDAOImpl.java
package org.fool.springhibernate.dao; import javax.annotation.Resource; import org.fool.springhibernate.model.Group; import org.fool.springhibernate.model.User; import org.springframework.stereotype.Repository; @Repository("userDAO") public class UserDAOImpl extends BaseDAOImpl<User> implements UserDAO { @Resource private GroupDAO groupDAO; @Override public void add(User user, int gid) { Group group = groupDAO.load(gid); user.setGroup(group); this.getSession().save(user); } @Override public long getGroupUserCount(int gid) { String hql = "select count(*) from User where group.id=?"; long count = (Long) this.getSession().createQuery(hql) .setParameter(0, gid).uniqueResult(); // String sql = "select count(*) from t_user where gid=?"; // // long count = (long) this.getSession().createSQLQuery(sql).setParameter(0, gid) // .uniqueResult(); return count; } @Override public void deleteByGroup(int gid) { String hql = "delete User u where u.group.id=?"; this.getSession().createQuery(hql).setParameter(0, gid).executeUpdate(); } }
5.src/test/java
TestSpringHibernate.java
package org.fool.springhibernate.test; import java.util.List; import javax.annotation.Resource; import org.fool.springhibernate.dao.GroupDAO; import org.fool.springhibernate.dao.UserDAO; import org.fool.springhibernate.model.Group; import org.fool.springhibernate.model.User; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:beans.xml") public class TestSpringHibernate { @Resource(name = "userDAO") private UserDAO userDAO; @Resource(name = "groupDAO") private GroupDAO groupDAO; @Test public void testAdd() { Group group = new Group(); group.setName("Test"); groupDAO.add(group); User user = new User("SpringHibernate", "456789", "SH"); userDAO.add(user, 10); } @Test public void testLoad() { Group group = groupDAO.load(3); System.out.println(group); } @Test public void testUpdate() { User user = userDAO.load(5); System.out.println(user); user.setNickname("HS"); userDAO.update(user); System.out.println(user); } @Test public void testDelete() { userDAO.delete(3); } @Test public void testList() { String hql1 = "from User u where u.username = ?"; String hql2 = "from Group"; List<User> users = userDAO.list(hql1, new Object[] { "SpringHibernate" }); List<Group> groups = groupDAO.list(hql2); for (User user : users) { System.out.println(user); } for (Group group : groups) { System.out.println(group); } } @Test public void testGetGroupUserCount() { Assert.assertEquals(6, userDAO.getGroupUserCount(10)); } @Test public void testDeleteByGroup() { userDAO.deleteByGroup(10); Assert.assertEquals(0, userDAO.getGroupUserCount(10)); } }