Spring Boot 中操作数据库入门

Spring Boot 中 Spring Data JPA

JPA是一个基于对象关系映射的标准规范。本文将介绍Spring Boot 与数据库相关简单操作的案例:

1、实战:

1、application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=wu25471396

#hibernate 提供了根据实体类自动维护数据库表结构的功能
spring.jpa.hibernate.ddl-auto=update
# 在控制台显示sql语句
spring.jpa.show-sql=true
# 让输出的Json字符串更美观
spring.jackson.serialization.indent-output=true

2、定义映射实体类

Hibernate支持自动将实体类映射为数据表格

@Entity     //表明这是一个与数据库表映射的实体
@NamedQuery(name = "Person.withNameAndAddressNamedQuery",
        query = "select p from Person p where p.name=?1 and address=?2 ")
public class Person {
    @Id     //主键
    @GeneratedValue     //主键自增,Hibernate 会为我们自动生成一个名为HIBERNATE_SEQUEMCE的序列
    private Long id;

    private String name;

    private Integer age;

    private String address;

    public Person() {
        super();
    }

    public Person(Long id, String name, Integer age, String address) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    // setter 和 getter 自己写
}

3、定义数据访问接口

public interface PersonRepository extends JpaRepository<Person, Long>{
    //使用方法名查询
   List<Person> findByAddress(String name);
   Person findByNameAndAddress(String name, String address);
    //使用@Query查询,参数按照名称绑定
   @Query("select p from Person p where p.name = :name and p.address = :address")
   Person withNameAndAddressQuery(@Param("name")String name,
                                   @Param("address")String address);
   //使用@namedQuery查询,即在实体类中做的@NamedQuery的定义
   Person withNameAndAddressNamedQuery(String name, String address);

}

5、本该定义业务逻辑层,但由于该入门程序没有复杂业务,本案例就省略了,书写web层
直接将PersonRepository注入到控制器中(以简化演示)。

@RestController
public class DataController {
    @Autowired
    PersonRepository personRepository;

    /**
     * 保存
     */
    @RequestMapping("/save")
    public Person save(String name, String address, Integer age) {
        Person p = personRepository.save(new Person(null, name, age, address));
        return p;
    }

    /**
     * 测试findByAddress
     */
    @RequestMapping("/q1")
    public List<Person> q1(String address) {
        List<Person> people = personRepository.findByAddress(address);
        return people;
    }

    /**
     * 测试findByNameAndAddress
     */
    @RequestMapping("/q2")
    public Person q2(String name, String address) {
        Person people = personRepository.findByNameAndAddress(name, address);
        return people;
    }

    /**
     * 测试withNameAndAddressQuery
     */
    @RequestMapping("/q3")
    public Person q3(String name, String address) {
        Person p = personRepository.withNameAndAddressQuery(name, address);
        return p;
    }

    /**
     * 测试withNameAndAddressNamedQuery
     */
    @RequestMapping("/q4")
    public Person q4(String name, String address) {
        Person p = personRepository.withNameAndAddressNamedQuery(name, address);
        return p;
    }

    /**
     * 测试排序
     */
    @RequestMapping("/sort")
    public List<Person> sort(){
        List<Person> people = personRepository.findAll(new Sort(Sort.Direction.ASC,"age"));
        return people;
    }

    /**
     * 测试分页
     */
    @RequestMapping("/page")
    public Page<Person> page() {
        Page<Person> pagePeople = personRepository.findAll(new PageRequest(1, 2));
        return pagePeople;
    }
}

2、Spring事务操作实战

1、业务层

@Service
public class DemoServiceImpl implements DemoService{
    @Autowired
    PersonRepository personRepository;

    @Transactional(rollbackFor={IllegalArgumentException.class})
    public Person savePersonWithRollBack(Person person) {
        Person p = personRepository.save(person);
        if(person.getName().equals("汪云飞")){
            throw new IllegalArgumentException("汪云飞以及存在,数据回滚");
        }
        return p;
    }

    @Transactional(noRollbackFor={IllegalArgumentException.class})
    public Person savePersonWithoutRollBack(Person person) {
        Person p = personRepository.save(person);
        if(person.getName().equals("汪云飞")) {
            throw new IllegalArgumentException("汪云飞以及存在,数据将不会回滚");
        }
        return p;
    }
}

2、控制器

@RestController
public class MyController {
    @Autowired
    DemoService demoService;

    @RequestMapping("/rollback")
    public Person rollback(Person person){
        return demoService.savePersonWithRollBack(person);
    }

    @RequestMapping("/norollback")
    public Person noRollback(Person person){
        return demoService.savePersonWithoutRollBack(person);
    }

}

3、Spring 缓存

CacheManager是Spring提供的各种缓存技术抽象接口。
Spring Boot缓存技术实战

业务逻辑:

@Service
public class DemoCacheServiceImpl implements DemoCacheService {

    @Autowired
    PersonRepository personRepository;

    @Override
    //@CachePut缓存新增的或更新的数据到缓存,其中缓存名为people,数据的key是person的id
    @CachePut(value = "people",key = "#person.id")
    public Person save(Person person) {
        Person p = personRepository.save(person);
        System.out.println("为Id、key为:"+p.getId()+"做了缓存");
        return p;
    }

    @Override
    //@CacheEvict从缓存people中删除key为id的数据
    @CacheEvict(value = "people")
    public void remove(Long id) {
        System.out.println("删除了id、key为"+id+"的数据缓冲");
        personRepository.deleteById(id);
    }

    @Override
    //@Cacheable 缓存key为person的id的数据到缓存pepple中
    @Cacheable(value = "people",key = "#person.id")
    public Person findOne(Person person) {
        Person p = personRepository.findById(person.getId()).orElse(null);
        System.out.println("为id、key为:"+p.getId()+"数据做了缓存");
        return p;
    }
}

控制层:

@RestController
public class CacheController {
    @Autowired
    DemoCacheService demoCacheService;

    @RequestMapping("/put")
    public Person put(Person person){
        return demoCacheService.save(person);
    }

    @RequestMapping("/able")
    public Person cacheable(Person person){
        return demoCacheService.findOne(person);
    }

    @RequestMapping("/evit")
    public String evit(Long id){
        demoCacheService.remove(id);
        return "OK";
    }
}

开启缓存支持:

@SpringBootApplication
@EnableCaching      //开启缓存支持
public class Ch82Application {

    public static void main(String[] args) {
        SpringApplication.run(Ch82Application.class, args);
    }
}

猜你喜欢

转载自blog.csdn.net/longge0508/article/details/80176760