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)); } }
相关推荐
下面将详细讲解Spring与Hibernate的集成及其在CRUD操作中的应用。 1. **Spring框架**:Spring 是一个全面的企业级应用开发框架,提供依赖注入(DI)、面向切面编程(AOP)、事务管理等核心功能。在本示例中,Spring...
在"Struts2整合Spring Hibernate的CRUD实例"中,我们将探讨如何将这三个框架无缝集成,实现对数据库的数据创建(Create)、读取(Read)、更新(Update)和删除(Delete)操作。下面将详细介绍这个实例中的关键知识...
Spring MVC Hibernate MySQL 数据库“打印机之家” 一个小型的Web应用程序,用于使用数据库表进行Crud操作。 开发者 艾尔·库尔皮金(IHOR KULPEKIN) 技术领域 编程语言: Java; 互联网技术: HTML,CSS,...
这个"springmvc spring hibernate整合Demo"旨在帮助初学者理解如何将这三个框架协同工作,实现一个完整的CRUD(创建、读取、更新、删除)应用。 Spring MVC 是 Spring 框架的一部分,专门用于构建Web应用程序。它...
在Spring中,CRUD操作通常通过集成Hibernate或JPA(Java Persistence API)等ORM(对象关系映射)框架来实现。这些框架允许开发者以面向对象的方式与数据库交互,而无需编写大量的SQL语句。 首先,我们需要配置...
**Spring进阶:Spring的CRUD** 在Java企业级开发中,Spring框架是不可或缺的一部分,它为应用程序提供了全面的控制反转(IoC)和面向切面编程(AOP)支持。Spring的CRUD操作,即创建(Create)、读取(Read)、更新...
"ext3+struts2+hibernate+spring的CRUD+分页"是一个典型的Java Web开发组合,用于实现全面的数据管理功能。这个组合充分利用了各个框架的优势,提供了一个强大的后端数据处理和前端展示的解决方案。 首先,EXT3是一...
Hibernate的Session API提供了CRUD操作,并且支持复杂的查询语句,包括HQL(Hibernate Query Language)和 Criteria API。 在Spring和Hibernate的整合中,Spring可以作为Hibernate的容器,管理SessionFactory和...
Struts_Spring__Hibernate_指导学生做ssh项目 简单易学_Struts_Spring__Hibernate_指导学生做ssh项目
在这个视频教程中,你可能将学习到如何配置Spring的XML上下文文件以启用注解驱动的配置,如何在Spring MVC中创建注解式的控制器并处理HTTP请求,以及如何通过Hibernate的注解来设计数据模型并执行CRUD操作。...
在这个“Struts_Spring_Hibernate_CRUD操作案例_分页查询”中,我们将深入探讨如何整合这三大框架实现数据的创建、读取、更新、删除(CRUD)以及分页查询。 1. **Struts框架**: - **Action类**:它是业务逻辑的...
通过定义DAO(数据访问对象)接口和实现类,我们可以利用Hibernate的API进行CRUD(创建、读取、更新、删除)操作,同时Spring的AOP可以方便地实现事务的开启、提交、回滚。 总的来说,这个例子旨在教会开发者如何将...
Hibernate通过JDBC与SQL Server进行交互,执行CRUD操作。 7. **整合过程**:SSH整合主要包括配置Struts的配置文件(struts-config.xml),Spring的配置文件(spring-beans.xml),以及Hibernate的配置文件(hibernate....
6. **依赖注入**:Spring框架可集成到Struts2和Hibernate中,实现依赖注入,提高代码的可测试性和可维护性。 这个项目是一个典型的Java Web开发示例,展示了如何使用Struts2和Hibernate实现CRUD操作,对初学者来说...
在这个案例中,"SpringMVC+Spring+Hibernate+Oracle 实现图书管理(CRUD)"是一个使用了四大主流Java技术栈的项目,分别是SpringMVC作为前端控制器、Spring作为应用层框架、Hibernate作为持久层框架,以及Oracle作为...
【Spring4-Struts2-Hibernate4 CRUD Demo_3】是一个综合性的开发示例,它展示了如何在Java Web应用程序中整合三大主流框架:Spring 4、Struts 2和Hibernate 4来实现CRUD(创建、读取、更新、删除)操作。这个Demo...
在本示例中,我们探讨的是一个基于Spring 3.2和Hibernate 4的完整CRUD(创建、读取、更新、删除)操作演示。这个压缩包文件包含了实现这一功能所需的全部资源,让我们深入理解如何将这两个强大的Java框架集成到实际...
在DAO实现类中,使用Spring的`@Autowired`注解注入SessionFactory,并通过SessionFactory创建Session,执行CRUD操作。 7. **Service层**:创建服务接口和实现类,封装业务逻辑,调用DAO层进行数据操作。这里可以...
Hibernate支持CRUD(Create、Read、Update、Delete)操作,还有HQL(Hibernate Query Language)用于执行复杂查询,提高了开发效率。 Struts框架: Struts是基于MVC设计模式的Web应用框架,它负责处理HTTP请求,...
【Spring4-Struts2-Hibernate4 CRUD Demo (1)】是一个典型的Java Web开发示例,它演示了如何集成Spring4、Struts2和Hibernate4框架来实现CRUD(创建、读取、更新和删除)操作。这个项目是初学者学习企业级应用开发的...