众所周知,Maven是整理项目的利器,它只需要通过配置文件来管理项目所需要的jar包。
SpringMVC是目前java开发的主流框架模式
hibernate是一个开放源代码的对象关系映射框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库
SpringData是依赖于hibernate的底层数据交互的基础方法,增删改查,排序和分页查询等等。
一 创建Maven工程
具体项目结构如下
创建后会有四个结构分支,[src/mian/java , src/main/resources , src/test/java , src/test/resources]
如果没有的自己进行创建即可, 选中项目右键 --> Bulid Path --> New Source Floder 创建即可。
二 配置Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVC整合hibernate和SpringData</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-hibernate.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>springMvc配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
三 Spring和hibernate的相关配置信息
文件: jdbcConfig.properties
#Mysql
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/imei?useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password = root
文件: spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 启用注解 -->
<context:annotation-config />
<!-- 指定注解扫描包结构 -->
<context:component-scan base-package="com.muang" />
<!-- 定义返回客户端视图(JSP)的位置 根据ACTION返回的字符串在VIEWS目录下进行查找 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
文件: spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 指定注解扫描包结构(主要用于junit单元测试,在spring-mvc.xml中配置即可) -->
<context:component-scan base-package="com.muang" />
<!-- 引入数据源配置信息 -->
<context:property-placeholder location="classpath:jdbcConfig.properties"/>
<!-- 1.配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 2.配置hibernate工厂 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/> <!-- 设置数据源 -->
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> <!-- 设置springdata jpa处理器 -->
<property name="packagesToScan" value="com.muang.entity"/> <!-- 这是指定实体类扫描路径 -->
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop> <!-- 是否控制台打印SQL -->
<prop key="hibernate.format_sql">true</prop> <!-- 是否格式化SQL -->
<prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 是否自动生成数据表 -->
</props>
</property>
</bean>
<!-- 配置Spring-data-jpa -->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/> <!-- 连接mysql -->
<property name="showSql" value="true"/> <!-- 是否打印SQL -->
<property name="generateDdl" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
<!-- 3.配置事物管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 4.配置支持注解的事物 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 5.配置Spring data -->
<jpa:repositories base-package="com.muang.dao"
entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager">
</jpa:repositories>
</beans>
四 配置pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.munag</groupId>
<artifactId>springdemo2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springdemo2 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring-version>4.0.3.RELEASE</spring-version>
<hibernate-version>4.3.5.Final</hibernate-version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- hibernate -->
<!-- https://mvnrepository.com/artifact/org.hibernate.common/hibernate-commons-annotations -->
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- spring -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- 其他 -->
<!-- https://mvnrepository.com/artifact/antlr/antlr -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.1.GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.transaction/jta -->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- webservice cxf -->
</dependencies>
<build>
<finalName>springdemo2</finalName>
</build>
</project>
五 使用Junit进行单元测试(tomcat启动访问地址也可以测试)
实体类代码(entity):
package com.muang.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="im_user")
public class User implements Serializable{
private static final long serialVersionUID = -463904210999570141L;
@Id //主键
@GeneratedValue //自动增长
private Integer id;
@Column(length = 40) // 自动创建字段是 指定长度为40
private String name;
@Column(length = 40)
private String acctor;
@Column(length = 40)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAcctor() {
return acctor;
}
public void setAcctor(String acctor) {
this.acctor = acctor;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
接口类代码(dao):
package com.muang.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.muang.entity.User;
/**
* 继承JpaRepository接口 实现 基础查询、排序、分页功能
* 继承JpaSpecificationExecutor 实现查询条件构造功能
*/
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>{
/**
* 实现Repository接口后, 某些方法可以自动查询, 底层会按照方法命名规则进行解析
* 具体常用的命名规则会在下面贴出来
*/
public List<User> findByName(String name);
@Query("select o from User o where acctor = ?1") //使用 '?序号' 占位符
public List<User> getNamesByAcctor(String acctor);
@Modifying // 执行update语句需要注解该注解
@Query("update User o set o.name = :name where o.id = :id") // 使用冒号占位符需要在参数前面注解 @Param
public void updateNameById(@Param("name") String name, @Param("id") Integer id);
}
服务类代码(service)
package com.muang.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.muang.dao.UserDao;
import com.muang.entity.User;
@Service
public class UserServiceImpl{
@Autowired
private UserDao dao;
/**
* 保存操作添加实物
*/
@Transactional
public void save(User user) {
dao.save(user);
}
/**
* 删除操作添加实物
* @param id
*/
@Transactional
public void deleteById(Integer id) {
dao.delete(id);
}
/**
* 接口自带的查询, 感兴趣可以看看源码
* @return
*/
public List<User> findAll() {
return dao.findAll();
}
public List<User> getNamesByAcctor(String acctor) {
return dao.getNamesByAcctor(acctor);
}
@Transactional //执行 insert/update/delete操作时候需要注解事务
public void updateNameById(String name, Integer id) {
dao.updateNameById(name, id);
System.out.println("保存成功!");
}
}
Junit方法测试类:
package com.muang.service;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.muang.dao.UserDao;
import com.muang.entity.User;
public class TestUserServiceImpl {
private ApplicationContext ctx = null;
private UserDao userDao = null;
private UserServiceImpl userServiceImpl = null;
@Before
public void setup() {
// 加载上下文
ctx = new ClassPathXmlApplicationContext("spring-hibernate.xml");
// 从容器中获取bean
userDao = ctx.getBean(UserDao.class);
userServiceImpl = ctx.getBean(UserServiceImpl.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
/**
* 测试添加操作
*/
@Test
public void saveUser(){
User user = new User();
user.setName("12");
user.setAcctor("admin");
user.setPassword("1234");
userDao.save(user);
}
/**
* 测试查询操作
*/
@Test
public void getNamesByAcctor(){
List<User> users = userDao.getNamesByAcctor("admin");
for (User user : users)
System.out.println("用户名:" + user.getName() + ", 账号 :" + user.getAcctor() + ", 密码:" + user.getPassword());
}
/**
* 测试删除操作
*/
@Test
public void deleteById(){
userDao.delete(5);
}
/**
* 测试修改操作
*/
@Test
public void updateNameById(){
userServiceImpl.updateNameById("zhangsan", 4);
}
}
选中方法,右键 Run as ---> Junit Test 执行。 执行结果如下
框架整合到这里就结束了, 上述只是基本的配置,整合其他框架技术还需要各位自己进行拓展。
PS:关于SpringData 方法接口命名规则可以参考下图:
有问题欢迎留言交流。