Spring-Spring-SpringJpa的掌握-scy

什么是三大框架三大框架:

ssh:struts spring hibernate

主流框架:ssm

ssm: SpringMVC Spring MyBatis

Spring+jpa整合:

整合步骤

1.先配置jdbc.properties --》dataSource -->EntityManagerFactory–>EntityManager–>TransactionManager

2.创建一个web的maven项目, 导入pom的依赖包

<dependencies>
    <!-- springmvc的支持--> 
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
     <!-- springjdbc的支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
     <!-- spring框架和orm框架整合需要的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
     <!-- jpa相关的jar包-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <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>
	<!-- springaop功能-->
    <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>
      <scope>test</scope>
    </dependency>
  </dependencies>

Bean对象注入:

jdbc.properties->dataSource->entityManagerFactory->dao->service->junit->action

加载jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssj
jdbc.username=root
jdbc.password=123456//对应自己数据库密码

<?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"
	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">

	<!-- 加载jdbc.properties -->
	<context:property-placeholder location="jdbc.properties" />
	

配置连接池datesource:

<!-- 配置连接池dataSource -->
<!-- destroy-method="close当前bean销毁的时候,会先调用close方法,关闭连接" -->
<bean id="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>

配置entityManagerFactory:

<!-- 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包 -->
	<!-- public void setPackagesToScan(String... packagesToScan) { -->
	<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>

声明事务管理:

<!-- 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包 -->
	<!-- public void setPackagesToScan(String... packagesToScan) { -->
	<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 id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 开启注解事务管理 ,解析@Transactional注解 -->
<!-- transaction-manager="transactionManager"默认找bean.id=transactionManager事务管理器 -->
<tx:annotation-driven />

配置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">

    <!-- 处理懒加载关闭问题 -->
    <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>
    <!-- 监听器读取配置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 字符编码过滤器-->
    <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>
    <!-- 核心控制器配置-->
    <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>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置applicationContext.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: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">
    <!-- 扫描 可以处理@Repository, @Service, and @Controller,@Autowired,@PersistenceContext 注解 -->
    <context:component-scan base-package="cn.itsource.ssj"></context:component-scan>
    <!--读取配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--连接池-->
    <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}" />
    </bean>

    <!--entityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- 注入连接池-->
        <property name="dataSource" ref="dataSource"></property>
        <!--扫描注解 entity-->
        <property name="packagesToScan" value="cn.itsource.ssj.domain"></property>
        <!-- 方言 是否显示sql  建表策略-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <!-- private boolean generateDdl = true;底层使用update策略-->
                <property name="generateDdl" value="true" />
                <!-- private String databasePlatform;原来方言 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
            </bean>
        </property>
    </bean>

    <!-- 事务控制 id必须这样取名 底层就是找名字 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>

    <!-- 扫描的注解 @Transaction-->
    <tx:annotation-driven ></tx:annotation-driven>




</beans>

applicationContext-mvc.xml:

<?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.controller"></context:component-scan>

    <!-- 静态资源放行-->
    <mvc:default-servlet-handler/>

    <!-- 扫描RequestMapping-->
    <mvc:annotation-driven/>

    <!-- 视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

配置jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///task//数据库名
jdbc.username=root//用户名
jdbc.password=123456//密码

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSSJ {
    //注入接口 product
    @Autowired
    IProductService productService;
    //注入接口
    @Autowired
    IProductDirService productDirService;

    @Test
        public void testSSJ()throws Exception{
        Product product = new Product();
        //给product给值
        product.setName("冯皇");
        ProductDir productDir = new ProductDir();
        productDir.setName("最强男人之一");
        //多对一,把productDir给product
        product.setProductDir(productDir);

        //使用添加方法
        //ProductDir要放在前,因为加载的时候会先去找Product,product放后面,不然报错
        productDirService.save(productDir);
        productService.save(product);

    }
}

domain(多对一)

Product类
@Entity
@Table(name="t_product")//数据库表名
public class Product {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    //多对一  懒加载
    @ManyToOne(fetch = FetchType.LAZY)
    //别名
    @JoinColumn(name="dir_id")
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

    private  ProductDir productDir;

    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 ProductDir getProductDir() {
        return productDir;
    }

    public void setProductDir(ProductDir productDir) {
        this.productDir = productDir;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", productDir=" + productDir +
                '}';
    }
}
ProductDir
@Entity
@Table(name="t_productdir")//数据库表名
public class ProductDir {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    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;
    }
}
Dao层(增删改查)
public interface IProductDao {
    //添加
    public  void save(Product product);
    //删除
    public  void delete(Long id);
    //修改
    public  void update(Product product);

    //查询一个
    public Product find(Long id);

    //查询全部
    public List<Product> findAll();
}
Dao实现增删改查
@Repository
public class IProductImpl  implements IProductDao {

    @PersistenceContext//通过持久化上下文得到entityManager
    private EntityManager entityManager;
    //添加
    public void save(Product product) {
        entityManager.persist(product);
    }
    //删除
    public void delete(Long id) {
        //先查找对象,看是否存在
        Product product = entityManager.find(Product.class, id);
        //如果值不为空,证明有值
        if(product!=null){
            //执行删除方法
            entityManager.remove(product);
        }
    }
    //修改
    public void update(Product product) {
        entityManager.merge(product);
    }

    public Product find(Long id) {
        //查询方法通过id查询
        return entityManager.find(Product.class,id);
    }

    public List<Product> findAll() {
        //查询全部需要先创建jpql语句
        String jpql="select o from Product o";
        //执行查询语句
        Query query =entityManager.createQuery(jpql);
        return query.getResultList();
    }
}

Service(服务层增删改查,切面,插入其他方法)

public interface IProductService {
    //添加
    public  void save(Product product);
    //删除
    public  void delete(Long id);
    //修改
    public  void update(Product product);

    //查询一个
    public Product find(Long id);

    //查询全部
    public List<Product> findAll();
}
Service实现
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class IProductServiceImpl implements IProductService {
    @Autowired
    //注入接口
    IProductDao productDao;

    @Transactional
    //事务方式运行
    public void save(Product product) {
        //添加
        productDao.save(product);
    }

    @Transactional
    //事务方式运行
    public void delete(Long id) {
        //删除
        productDao.delete(id);
    }

    @Transactional
    //事务方式运行
    public void update(Product product) {
        //修改
        productDao.update(product);
    }

    public Product find(Long id) {
        return productDao.find(id);
    }

    public List<Product> findAll() {
        return productDao.findAll();
    }
}
Controller(控制层,页面跳转)
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    IProductService productService;

    //跳转到前段页面
    @RequestMapping("/index")
    public String index() {
        //跳转到前台product.jsp界面
        return "product";
    }

    //跳转到前段页面
    @RequestMapping("/list")
    @ResponseBody
    public List<Product> list() {
        System.out.println(productService.findAll());
        //返回前台json数据
        return productService.findAll();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值