SSJ集成&声明式事务管理

三大框架

ssh:Struts Spring Hibernate
ssm:SpringMVC Spring MyBatis
ssj:
SpringMVC Spring JPA(今天学习)
Struts2 Spring JPA
SpringMVC Spring spring Data JPA(spring的全家桶)

Spring集成JPA(SpringMVC Spring JPA)

依赖包

<dependencies>
	<!--Spring支持包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <!--SpringMVC支持包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <!--jdbc支持包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <!--对象关系映射-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <!--hibernate核心包-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <!--hibernate Jpa整合-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <!--mySql依赖包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
     <!--连接池依赖-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!--spring 测试包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
	<!--Aop依赖包-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>
    <!--json支持包-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.5</version>
    </dependency>
    <!--测试包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>

写一个domain对象,配置JPA映射

@Entity
@Table(name = "t_product")
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dir_id")
    //忽略延迟加载额外生成的handler这个属性
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private ProductDir dir;

后面要用的多对一产品同理创建domain以及对应的三层

@Entity
@Table(name="t_productDir")
public class ProductDir {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

Spring 的配置文件

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssj
jdbc.username=root
jdbc.password=123456

applicationContext.xml

bean对象的注入顺序:jdbc.properties->dataSource->entityManagerFactory->dao->service->junit->action
在spring的配置文件添加一点事务配置,并且在service层类上面添加一些注解,就可以实现事务管理
<?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"
       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">

    <!-- 扫描dao、service、action组件 -->
    <!-- 可以处理@Repository, @Service, and @Controller,@Autowired,@PersistenceContext 注解-->
    <context:component-scan base-package="cn.itsource.ssj"></context:component-scan>

    <!-- 加载jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- 配置连接池dataSource -->
    <!-- destroy-method="close当前bean销毁的时候,会先调用close方法,关闭连接" -->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!-- 依赖注入连接池需要的属性 -->
        <!-- property name="是BasicDataSource的set方法,本质属性" -->
        <!-- property value="是jdbc.properties配置文件的key" -->
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter引入默认entityManagerFactory名称 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- 1.注入DataSource -->
        <property name="dataSource" ref="dataSource" />
        <!-- 2.从哪个包去扫描@Entity,domain包 -->
        <property name="packagesToScan" value="cn.itsource.ssj.domain" />
        <!-- 3.配置JPA的实现 -->
        <!-- private JpaVendorAdapter jpaVendorAdapter; setJpaVendorAdapter()  private OtherBean otherBean -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter -->
                <!-- private boolean showSql = false;是否显示sql语句 -->
                <property name="showSql" value="true" />
                <!-- private boolean generateDdl = false;是否建表 数据定义语言 -->
                <property name="generateDdl" value="true" />
                <!-- private String databasePlatform;原来方言 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
            </bean>
        </property>
    </bean>
    <!--添加事务配置-->
    <bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>
    <!-- 开启注解事务管理 ,解析@Transactional注解 -->
    <!-- transaction-manager="transactionManager"默认找bean.id=transactionManager事务管理器 -->
    <tx:annotation-driven />
</beans>

IProductDao

public interface IProductDao {
	void save(Product product);

	void update(Product product);

	void delete(Long id);

	Product get(Long id);

	List<Product> getAll();
}

ProductDaoImpl

@Repository
public class ProductDaoImpl implements IProductDao {

	// @Autowired 不能使用这个注入
	@PersistenceContext // 持久层上下文管理器
	private EntityManager entityManager;

	@Override
	public void save(Product product) {
		entityManager.persist(product);
	}
	@Override
	public void update(Product product) {
		entityManager.merge(product);
	}
	@Override
	public void delete(Long id) {
		Product product = get(id);
		if (product != null) {
			entityManager.remove(product);
		}
	}
	@Override
	public Product get(Long id) {
		return entityManager.find(Product.class, id);
	}
	@Override
	public List<Product> getAll() {
		String jpql = "select o from Product o";
		return entityManager.createQuery(jpql).getResultList();
	}

}

IProductService

public interface IProductService {
	void save(Product product);

	void update(Product product);

	void delete(Long id);

	Product get(Long id);

	List<Product> getAll();
}

ProductServiceImpl

@Service
// 默认事务配置
// @Transactional
// 上面配置等价于下面配置
@Transactional(propagation = Propagation.REQUIRED)
public class ProductServiceImpl implements IProductService {
	@Autowired
	private IProductDao productDao;
	@Override
	public void save(Product product) {
		productDao.save(product);
	}
	@Override
	public void update(Product product) {
		productDao.update(product);
	}
	@Override
	public void delete(Long id) {
		productDao.delete(id);
	}
	@Override
	@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
	public Product get(Long id) {
		return productDao.get(id);
	}
	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Product> getAll() {
		return productDao.getAll();
	}
}

Juit

@Autowired
IProductService productService;

@Test
public void save() throws Exception {
	System.out.println("代理类:" + productService.getClass());
	Product product = new Product();
	product.setName("苹果的弟弟");
	productService.save(product);
}
代理类:class com.sun.proxy.$Proxy23

Spring集成SpringMVC

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--监听器 Listener javaweb 可以监听四大作用生命周期 和 作用域属性操作
        就可以读取的配置文件 contextConfigLocation 为key value applicationContext.xml
    -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--Spring核心控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
    <!-- 优先加载servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
    <!-- 配置过滤器 解决懒加载延迟关闭问题-->
    <filter>
        <filter-name>openEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>openEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <!--编码过滤器配置-->
  <filter>
    <filter-name>encodingFilter</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>forEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

配置SPringMvc

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
">
    <!-- 扫描controller 静态资源放行  视图解析器 上传下载解析-->
    <context:component-scan base-package="cn.itsource.ssj.web"></context:component-scan>
    <!--静态资源放行-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--开启注解支持  扫描@RequestMapping-->
    <mvc:annotation-driven></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>

##ProductController

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
    @RequestMapping("/list")
    @ResponseBody
    public List<Product> findAll() {
        System.out.println("---------");
        System.out.println(productService.findAll());
        return productService.findAll();
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="/easyui/themes/icon.css">
    <script type="text/javascript" src="/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
       //格式化列的方法
        function objFormat(obj){
            if(obj != null){
                return obj.name;
            }
        }
    </script>
</head>
<body>

<table id="productGrid" class="easyui-datagrid" style="width:400px;height:250px"
       data-options="url:'/product/list',fitColumns:true,singleSelect:true,fit:true,toolbar:'#tt'">
    <thead>
    <tr>
        <th data-options="field:'id',width:100">编码</th>
        <th data-options="field:'name',width:100">名称</th>
        <th data-options="field:'dir',width:100,formatter:objFormat">产品分类</th>
        <%--  <th data-options="field:'productDir',width:100,align:'right',formatter:objFormat">产品</th>--%>
    </tr>
    </thead>

    <div id="tt">
        <a href="javascript:;" class="easyui-linkbutton" data-method="save">添加</a>
        <a href="javascript:;" class="easyui-linkbutton" data-method="update" >修改</a>
        <a href="javascript:;" class="easyui-linkbutton" data-method="delete">删除</a>
    </div>
</table>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值