springboot-5-整合jpa

########
##springboot-parent.version: 1.5.2
## jdk 1.8
## #######

 

在整合jpa之前, 先说下mysql

步骤: 

  1), 在application.properties中加入datasource配置

  2), 在pom.xml中加入mysql依赖

  3), 获取datasource的connection测试

 

 

然后, 配置连接池为druid

  1), pom.xml中引入依赖    

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
</dependency>

  2), 配置application.properties数据源类型

  3), 编写druid servlet和filter提供监控页面访问

 

 

jpa, 是一种规范, hibernate是他的一种实现方式

jpa是一种关于数据操作的 orm 对象/关系映射规范

 

1, 引入依赖

<!-- 整合jpa使用 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Spring Boot JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

 

2, 在src/main/source创建配置文件

application.yml

##### jpa #######
spring: 
  datasource: 
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    database: MYSQL
    show-sql: true
    hibernate:
      ddl-auto: update
#      naming:
#        implicit-strategy: org.hibernate.cfg.ImprovedNamingStrategy
    properties:   # 默认
      hibernate: 
        dialect: org.hibernate.dialect.MySQL5Dialect

 

3, 在实体类上加入@Entity, 就可以进行crud操作了

package com.iwhere.test.demo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

// 生成表结构 @Entity
// 表名, 不写默认为类名 @Table(name
="demo") public class Demo {

  // 主键 @Id

  // 主键生成策略 @GeneratedValue(strategy
=GenerationType.AUTO) private Integer id; @NotNull private String name; @Column(nullable=false) private String sex; public Integer getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public void setId(Integer id) { this.id = id; } }

4, dao层继承接口即可

package com.iwhere.test.dao;

import org.springframework.data.repository.CrudRepository;

import com.iwhere.test.demo.Demo;

/**
 * 使用crud接口的dao层
 * @author 231
 *
 */
public interface DemoRepository extends CrudRepository<Demo, Long> {

}

5, service层调用

package com.iwhere.test.service;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.iwhere.test.dao.DemoRepository;
import com.iwhere.test.demo.Demo;

/**
 * service层
 * @author 231
 */
@Service
public class DemoService {

    @Resource
    private DemoRepository demoRepository;
    
    @Transactional
    public void save(Demo demo)     {
        demoRepository.save(demo);
    }
    
}

6, controller层执行

package com.iwhere.test.web;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.iwhere.test.demo.Demo;
import com.iwhere.test.service.DemoService;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private DemoService demoService;
    
    /**
     * 返回json格式数据
     * @RestController
     * @return
     */
    @RequestMapping("/getDemo")
    public Demo getDemo() {
        Demo demo = new Demo();
        demo.setId(1);
        demo.setName("Angel");
        return demo;
    }
    
    /**
     * 测试jpa的使用
     * @return
     */
    @RequestMapping("/save")
    public String saveDemo() {
        Demo demo = new Demo();
        demo.setId(1);
        demo.setName("Angel");
        demo.setSex("female");
        demoService.save(demo);
        return "ok";
    }
    
  /**测试自定义异常*/
// @RequestMapping("/zeroExcetpion") // public int zeroException() { // System.err.println("zero"); // return 1/0; // } }

此时运行, 既可以在数据库看到demo的存入了

 

 

然后,  介绍下repository接口: 

1, 空接口, 标记
2, 继承Repository接口后, 会被IOC容器识别为一个bean
3, 也可用@RepositoryDefinition注解来代替继承
4, 方法名即sql语句
5, 条件树形要用关键字链接
6, 可以使用@Query实现自定义jpql语句

jpa操作为接口操作, 一个方法既一个sql语句, 常见的接口如下表:

具体的关键字,使用方法和生产成SQL如下表所示: 原文地址: http://www.cnblogs.com/ityouknow/p/5891443.html

KeywordSampleJPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

 

分页查询

分页查询在实际使用中非常普遍了,spring data jpa已经帮我们实现了分页的功能,在查询的方法中,需要传入参数Pageable
,当查询中有多个参数的时候Pageable建议做为最后一个参数传入

Page<User> findALL(Pageable pageable);
    
Page<User> findByUserName(String userName,Pageable pageable);

 

Pageable 是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则

@Test
public void testPageQuery() throws Exception {
    int page=1,size=10;
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    userRepository.findALL(pageable);
    userRepository.findByUserName("testName", pageable);
}

 

 

 

 

 

 

 

 

posted @ 2017-03-14 13:41  bronk  阅读(580)  评论(0编辑  收藏  举报