SpringMVC/Struts/Struts2 + Spring + JPA
第一步 新建web项目

pom.xml中JDK1.7 改成1.8

第二步:导包
Spring对web部分的支持 4.2.5
Spring对webMVC的支持4.2.5
aop织入包1.8.8
spring对jdbc支持4,2,5
spring和jpa集成(所需ORM包)4.2.5
junit包
Spring和AOP的集成包
Hibernate核心包
数据库驱动包5,1,6
连接池包1.2.2
SpringMVC返回Json的包
拷贝网址:https://www.jianshu.com/p/ecbf0c37cb08
第三步 :创建结构

第四步 :编写applicationContext.xml
①新建jdbc.properties(并且引入)---->连接数据库的配置


②配置DataSource(数据源,连接池)----->DBCP的数据源

③配置EntityManagerFactory【把核心对象交给Spring管理】--- 关键步骤
alt + insert ----> jpa ----->第二个(entityManagerFactory)

需要四大金刚 + 方言 + 显示SQL + 建表策略
扫描 packagerToScan value = domain完全限定名
适配器jpaVendorAdapter value = HIbernateJpaVendorAdapter完全限定名
方言找 value = MySQLDialect完全限定名
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="cn.zx.ssj.domain"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
④Domain,Dao,Service 等 ---- >不要求第四步写,随时可以写
Domain
@Entity
@Table(name = "t_product")
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
Test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SsjTest {
@Autowired
public EntityManagerFactory factory;
@Test
public void test() throws Exception{
System.out.println(factory);
}
}
测试结果图


Dao
增Save
删delete
改Update
查一条FindOne
查全部 FindAll
public interface IEmployeeDao {
void save(Employee emloyee);
void updata(Employee emloyee);
void delete(Long id);
Employee FindOne(Long id);
List<Employee> FindAll();
}
@Repository
public class EmployeeDaoImpl implements IEmployeeDao{
/*
Persistence(持久化)Context (上下文)....Spring看到这里需要一个EntityManager,
如果找到了就直接给你,如果没找到就创建一个给你
*/
@PersistenceContext
private EntityManager entityManager;
@Override
public void save(Employee employee) {
entityManager.persist(employee);
}
@Override
public void updata(Employee employee) {
entityManager.merge(employee);
}
@Override
public void delete(Long id) {
Employee employee = FindOne(id);
if (employee != null){
entityManager.remove(employee);
}
}
@Override
public Employee FindOne(Long id) {
return entityManager.find(Employee.class,id );
}
@Override
public List<Employee> FindAll() {
return entityManager.createQuery("select o from Employee o").getResultList();
}
}

service
xml中添加扫描service包
public interface IEmployeeService {
void save(Employee employee);
void updata(Employee employee);
void delete(Long id);
Employee FindOne(Long id);
List<Employee> FindAll();
}
@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService{
@Autowired
private IEmployeeDao employeeDao;
@Override
public void save(Employee employee) {
employeeDao.save(employee);
}
@Override
public void updata(Employee employee) {
employeeDao.updata(employee);
}
@Override
public void delete(Long id) {
employeeDao.delete(id);
}
@Override
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public Employee FindOne(Long id) {
return employeeDao.FindOne(id);
}
@Override
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public List<Employee> FindAll() {
return employeeDao.FindAll();
}
}
注意事项
1、事务应该开在service(业务才应该是原子操作)
2、EntityManager对象不能够由我自己创建
⑤搞事务 (根据AOP把事务全部加进去)
xml添加事务管理器
alt + insert ----> jpa ----->第四个(transactionManager)




⑥集成SpringMVC(applicationContext-mvc.xml web.xml Contrller)
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描controller-->
<context:component-scan base-package="cn.zx.ssj.controller"/>
<!--静态资源放行-->
<mvc:default-servlet-handler/>
<!--MVC注解支持-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>




①扫描controller

②静态资源放行(图片、css、js)

③MVC注解支持

④视图解析器

⑤上传解析器
⑦web.xml
要改成2.4。头有些不好 直接拷贝一个即可
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app id="WebApp_ID" version="3.1"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!--springMVC?????? ====???SpringMVC -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--??SpringMVC?????-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<!--?????tomcat?????????-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--??/????RESTful?????-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--??Spring??ContextLoaderListener??Spring????-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--??Spring?xml ===>??Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--????-->
<!--??????????????????????-->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
①SpringMVC核心控制器
②乱码问题解决

③读取Spring的xml ---- > 启动Spring


⑧controller
/**
* @Controller --- 这是个控制层
* @RequestMapping("") ---- 路径
* @ResponseBody --- 要返回json一定要加注解
*/
@Controller
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private IEmployeeService employeeService;
@RequestMapping("index")
public String index(){
return "index";
}
// 要返回json一定要加注解---@ResponseBody
@RequestMapping("list")
@ResponseBody
public List<Employee> list(){
return employeeService.FindAll();
}
@RequestMapping("delete")
@ResponseBody
public Boolean delete(Long id){
try {
employeeService.delete(id);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
⑨前端页面
employee.js
//页面读取完毕后执行
$(function(){
//常用的组件先获取到
var productGrid = $("#productGrid");
//所有带来data-cmd属性的元素都加上方法
$("*[data-cmd]").on("click",function(){
//谁点击,this就是谁
var methodName = $(this).data("cmd");
//执行这个方法(动态调用)
zx[methodName]();
})
zx = {
add(){ alert("add")},
edit(){alert("edit")},
delete(){
//1.获取选中的行(第一个参数是方法名)
var row = productGrid.datagrid("getSelected");
//2.如果没有这一行,给出提示
if(!row){
$.messager.alert('提示','请选择后再操作',"info");
return;
}
//3.如果有这一行,给出提示
$.messager.confirm('确认','您真的要狠心删除我嘛?',function(r){
if (r){
//4.如果确定要删除,发送(Ajax)请求进行删除
$.post("/employee/delete",{id:row.id},function(result){
//5.删除完成后,成功就删除,失败就给提示
if(result){
//重新加载页面
productGrid.datagrid("reload");
}else{
$.messager.alert('提示','小伙子,以后努力',"error");
}
})
}
});
}
};
})
index.jsp
<%--
Created by IntelliJ IDEA.
User: surho
Date: 2019/8/28
Time: 19:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--easyui的css样式--%>
<link rel="stylesheet" type="text/css" href="/easyui/themes/default/easyui.css">
<%--easyui的图标支持--%>
<link rel="stylesheet" type="text/css" href="/easyui/themes/icon.css">
<%--jQuery的支持--%>
<script type="text/javascript" src="/easyui/jquery.min.js"></script>
<%--easyui的核心功能--%>
<script type="text/javascript" src="/easyui/jquery.easyui.min.js"></script>
<%--中文支持--%>
<script src="/easyui/locale/easyui-lang-zh_CN.js"></script>
<%--引入自己的js--%>
<script src="/js/model/employee.js"></script>
</head>
<body>
<table id="productGrid" class="easyui-datagrid"
data-options="url:'/employee/list',fitColumns:true,singleSelect:true,fit:true,toolbar:'#tb'">
<thead>
<tr>
<th data-options="field:'id',width:100">编码</th>
<th data-options="field:'name',width:100">名称</th>
</tr>
</thead>
</table>
<div id="tb">
<a href="#" data-cmd="add" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a>
<a href="#" data-cmd="edit" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">修改</a>
<a href="#" data-cmd="delete" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">删除</a>
</div>
</body>
</html>
⑩安装Tomcat并运行
学习地址:
单词
Scan--- 扫描
databasePlatform --- 方言
generateDdl --- 建表策略
showSql--- 是否显示Sql
Tx --- 事务
a
注解
@PersistenceContext --- 持久化上下文


java育儿园里的小学生“磨陀货”友情提供!! 不用谢不用谢 诶~不用不用 真不用谢! 记得点赞赞赞赞
![]()
网友评论