前言:本文将通过一个小程序来实现sss框架整合(省略web页面)
1、maven依赖
<!--Spring+SpringMVC+SpringData JPA -->
<dependencies>
<!--Spring Data JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.3.RELEASE</version>
</dependency>
<!--Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!--Hibernate -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!--Servlet -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp -->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--MySQL数据库驱动 -->
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.2</version>
</dependency>
<!--FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
2、persistence.xml(springData的jpa配置)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="dbconfig">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<!--配置数据库驱动 -->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<!--配置数据库url -->
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/1710_sss?characterEncoding=UTF-8" />
<!--配置数据库用户名 -->
<property name="hibernate.connection.username" value="lx" />
<!--配置数据库密码 -->
<property name="hibernate.connection.password" value="lx" />
<!--配置Hibernate方言 -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect" />
<!--设置外连接抓取树的最大深度 -->
<property name="hibernate.max_fetch_depth" value="10" />
<!--自动输出schema创建DDL语句 -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="javax.persistence.validation.mode" value="none"/>
</properties>
</persistence-unit>
</persistence>
3、applicationContext.xml(spring配置)
<?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:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- 开启IOC注解扫描 -->
<context:component-scan base-package="com.qf">
<!--排除SpringMVC的控制器扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--配置JPA核心管理对象 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--配置持久化的模块名称 -->
<property name="persistenceUnitName" value="dbconfig"></property>
<!--加载持久化的配置文件 -->
<property name="persistenceXmlLocation" value="classpath:persistence.xml"></property>
<!--设置JPA的适配器 -->
<property name="jpaVendorAdapter">
<!--基于Hibernate的JPA -->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 启用 annotation事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置Spring Data JPA扫描目录 -->
<!-- 自动扫描并注入Spring Data JPA -->
<jpa:repositories base-package="com.qf"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager" >
</jpa:repositories>
</beans>
4、springMVC.xml(springMVC配置)
<?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:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描使用注解的类:创建控制器对象 -->
<context:component-scan base-package="com.qf.web"></context:component-scan>
<!--视图解析器,可以设置页面的前缀和后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="prefix" value="/WEB-INF/views/"></property> -->
<!-- <property name="suffix" value=".jsp"></property> -->
</bean>
<!--注册转换器 -->
<mvc:annotation-driven>
<!--数据转换 -->
<mvc:message-converters register-defaults="true">
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:constructor-arg value="UTF-8"/>
</beans:bean>
<!-- 配置Fastjson支持 -->
<beans:bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<beans:property name="charset" value="UTF-8"/>
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>application/json</beans:value>
<beans:value>text/html;charset=UTF-8</beans:value>
</beans:list>
</beans:property>
<beans:property name="features">
<beans:list>
<beans:value>WriteMapNullValue</beans:value>
<beans:value>QuoteFieldNames</beans:value>
<beans:value>WriteDateUseDateFormat</beans:value>
<beans:value>WriteEnumUsingToString</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--放行静态资源 -->
<mvc:default-servlet-handler/>
<!--资源重定向,解决的是浏览器无法访问INF目录下的资源 -->
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/WEB-INF/images/" mapping="/images/**"></mvc:resources>
</beans>
5、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>M_SpringData_JPA</display-name>
<!--Spring的配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--SpringMVC的配置 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--编码过滤器的配置 -->
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>listitem.jsp</welcome-file>
</welcome-file-list>
</web-app>
6、domain层(实体层)
@Entity
@Table(name="t_item")
//命名查询JPQL
@NamedQuery(name="Item.getAll",query="from Item")
public class Item {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(length=20)
private String name;//名称
@Column(length=20)
private String type;//型号
@Column(length=2)
private String uint;//单位
private int count;//数量
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUint() {
return uint;
}
public void setUint(String uint) {
this.uint = uint;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
7、dao层(
数据持久层实现有多种方法,本文给出两种)
7.1(第一种只需继承父类即可,自动匹配查询方法,如下)
public interface ItemDao extends JpaRepository<Item, Serializable>{
}
7.2(第二种根据方法命名查询对应sql)
public interface ItemQueryDao extends Repository<Item, Serializable>,JpaSpecificationExecutor<Item> {
//方法命名查询,自动生成JPQL
//根据id查询数据
List<Item> findById(Long id);
//在xxx之间
List<Item> findByCountBetween(int min,int max);
//大于小于
List<Item> findByIdGreaterThanAndIdLessThan(Long min,Long max);
//模糊查询
List<Item> findByNameLikeOrderByIdDesc(String name);
//以xxx开始
List<Item> findByNameStartingWith(String name);
//手动查询语句
//JPQL
@Query(value="from Item i where i.type=:type")
List<Item> queryByType(@Param("type")String t);
//SQL
@Query(value="select * from t_item where uint=?1",nativeQuery=true)
List<Item> queryByUint(String uint);
@Modifying
@Query(value="update t_item set name=?1 where id=?2",nativeQuery=true)
void updateName(String name,Long id);
//使用命名查询,也就是调用映射类上的指定的@NamedQuery
List<Item> getAll();
}
8、service层(业务逻辑层)
public interface ItemService {
//基本操作
//新增
public boolean save(Item item);
//修改
public boolean update(Item item);
//查询
public List<Item> queryAll();
//根据id查询对象
public Item queryById(Long id);
//删除
public void delete(Long id);
//方法名检索查询
List<Item> findById(Long id);
List<Item> findByCountBetween(int min,int max);
List<Item> findByIdGreaterThanAndIdLessThan(Long min,Long max);
List<Item> findByNameLike(String name);
List<Item> findByNameStartingWith(String name);
//手动查询
//JPQL
List<Item> queryByType(String type);
//SQL
List<Item> queryByUint(String uint);
//修改
void updateName(String name,Long id);
//命名查询
List<Item> getAll();
//Specification查询方式
List<Item> getAllByS();
}
9、serviceImpl层(业务实现层)
@Service
@Transactional
public class ItemServiceImple implements ItemService{
@Autowired
private ItemDao dao;
//各种查询方式
@Autowired
private ItemQueryDao dao2;
@Override
public boolean save(Item item) {
// TODO Auto-generated method stub
return dao.save(item)!=null?true:false;
}
@Override
public List<Item> queryAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
@Override
public void delete(Long id) {
// TODO Auto-generated method stub
dao.delete(id);;
}
@Override
public boolean update(Item item) {
// TODO Auto-generated method stub
return dao.save(item)!=null?true:false;
}
@Override
public Item queryById(Long id) {
// TODO Auto-generated method stub
return dao.findOne(id);
}
@Override
public List<Item> findById(Long id) {
// TODO Auto-generated method stub
return dao2.findById(id);
}
@Override
public List<Item> findByCountBetween(int min, int max) {
// TODO Auto-generated method stub
return dao2.findByCountBetween(min, max);
}
@Override
public List<Item> findByIdGreaterThanAndIdLessThan(Long min, Long max) {
// TODO Auto-generated method stub
return dao2.findByIdGreaterThanAndIdLessThan(min, max);
}
@Override
public List<Item> findByNameLike(String name) {
// TODO Auto-generated method stub
return dao2.findByNameLikeOrderByIdDesc(name);
}
@Override
public List<Item> findByNameStartingWith(String name) {
// TODO Auto-generated method stub
return dao2.findByNameStartingWith(name);
}
@Override
public List<Item> queryByType(String type) {
// TODO Auto-generated method stub
return dao2.queryByType(type);
}
@Override
public List<Item> queryByUint(String uint) {
// TODO Auto-generated method stub
return dao2.queryByUint(uint);
}
@Override
public void updateName(String name, Long id) {
// TODO Auto-generated method stub
dao2.updateName(name, id);
}
@Override
public List<Item> getAll() {
// TODO Auto-generated method stub
return dao2.getAll();
}
@Override
public List<Item> getAllByS() {
//专门的查询接口
return dao2.findAll(new Specification<Item>() {
//生成语句
/**
* 参数说明:
* 1、类的封装操作,如果需要使用类的属性,就直接使用get方法
* 2、查询条件拼接
* 3、查询条件的选择
* */
@Override
public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//获取指定属性的信息
Path<Long> id = root.get("id");
Path<String> type = root.get("type");
//连接查询
//root.join(" DataDict d",JoinType.INNER);
//return query.where(cb.and(cb.like(type, "%药%"),cb.le(id,3))).getRestriction();
return cb.and(cb.like(type, "%药%"),cb.le(id,3));
}
}, new Sort(Direction.DESC,"id"));
}
}
10、controller层(控制器层,对应上述两种dao层实现方式,控制器分为两个)
10.1、对应第一种无需手动写方法的dao实现
@Controller
public class ItemController {
@Autowired
private ItemService service;
//动态路径
@RequestMapping("{viewname}")
public String index(@PathVariable String viewname) {
return viewname;
}
//新增
@RequestMapping("/addItem")
public String add(Item item) {
item.setUpdateTime(new Date());
if(service.save(item)) {//成功就跳转到列表页
return "queryItem";
}else {//失败就返回
return "additem.jsp";
}
}
//查询
@RequestMapping("queryItem")
public String query(Model model) {
model.addAttribute("items", service.queryAll());
return "listitem.jsp";
}
//删除
@RequestMapping("deleteItem")
public String query(Long id) {
service.delete(id);
return "queryItem";
}
//修改
@RequestMapping("updateItem")
public String update(Item item) {
item.setUpdateTime(new Date());
if(service.update(item)) {
return "queryItem";
}else {
return "updateitem.jsp";
}
}
//修改页面跳转
@RequestMapping("updateById")
public String queryById(Long id,Model model) {
model.addAttribute("item", service.queryById(id));
return "updateitem.jsp";
}
}
10.2
、对应第二种手动写方法的dao实现
@Controller
public class ItemQueryController {
@Autowired
private ItemService service;
//基于方法命名
@RequestMapping("queryById")
public String queryById(Long id,Model model) {
model.addAttribute("items", service.findById(id));
return "listitem.jsp";
}
@RequestMapping("queryBetCount")
public String queryBetCount(int min,int max,Model model) {
model.addAttribute("items", service.findByCountBetween(min, max));
return "listitem.jsp";
}
@RequestMapping("queryLtId")
public String queryLtId(Long min,Long max,Model model) {
model.addAttribute("items", service.findByIdGreaterThanAndIdLessThan(min, max));
return "listitem.jsp";
}
@RequestMapping("queryLikeName")
public String querylikeName(String name,Model model) {
model.addAttribute("items", service.findByNameLike("%"+name+"%"));
return "listitem.jsp";
}
@RequestMapping("querySwName")
public String queryStName(String name,Model model) {
model.addAttribute("items", service.findByNameLike(name+"%"));
return "listitem.jsp";
}
//手动查询
//JPQL查询---面向对象查询
@RequestMapping("queryByType")
public String queryByType(String type,Model model) {
model.addAttribute("items", service.queryByType(type));
return "listitem.jsp";
}
//SQL查询---面向对象查询
@RequestMapping("queryByUint")
public String queryByUint(String uint,Model model) {
model.addAttribute("items", service.queryByUint(uint));
return "listitem.jsp";
}
//SQL修改
@RequestMapping("updateNameById")
public String update(String name,Long id,Model model) {
service.updateName(name, id);
return "queryItem";
}
//命名查询
@RequestMapping("getAll")
public String getAll(Model model) {
model.addAttribute("items", service.getAll());
return "listitem.jsp";
}
//Specification查询
@RequestMapping("getAllBys")
public String getAllBys(Model model) {
model.addAttribute("items", service.getAllByS());
return "listitem.jsp";
}
}