JPA 是 JCP 组织发布的 Java EE 标准之一,因此任何声称符合 JPA 标准的框架都遵循同样的架构,提供相同的访问API,这保证了基于JPA开发的企业应用能够经过少量的修改就能够在不同的JPA框架下运行。
JPA的查询语言是面向对象而非面向数据库的,它以面向对象的自然语法构造查询语句,可以看成是Hibernate HQL的等价物。JPA定义了独特的JPQL(Java Persistence Query Language),JPQL是EJB QL的一种扩展,它是针对实体的一种查询语言,操作对象是实体,而不是关系数据库的表,而且能够支持批量更新和修改、JOIN、GROUP BY、HAVING 等通常只有 SQL 才能够提供的高级查询特性,甚至还能够支持子查询。
package com.programb.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.*;
@ComponentScan(basePackages ="com.programb.example")
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
package com.programb.example.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "Person")
public class Person implements Serializable {
private static final long serialVersionUID = 133938246231808718L;
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
private String address;
public Person() {
super();
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Person(Long id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name=" + name +
", age=" + age +
", address=" + address +
'}';
}
}
package com.programb.example.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.programb.example.bean.Person;
import com.programb.example.service.DemoService;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class CacheConfig {
@Autowired
private DemoService demoService;
@Bean
public CacheManager getCacheManager() {
List<Person> personList = demoService.findAll();
//所有缓存的名字
List<String> cacheNames = new ArrayList();
GuavaCacheManager cacheManager = new GuavaCacheManager();
//GuavaCacheManager 的数据结构类似 Map> map =new HashMap<>();
//将数据放入缓存
personList.stream().forEach(person -> {
//用person 的id cacheName
String cacheName=person.getId().toString();
if(cacheManager.getCache(cacheName)==null){
//为每一个person 如果不存在,创建一个新的缓存对象
cacheNames.add(cacheName);
cacheManager.setCacheNames(cacheNames);
}
Cache cache = cacheManager.getCache(cacheName);
//缓存对象用person的id当作缓存的key 用person 当作缓存的value
cache.put(person.getId(),person);
System.out.println("为 ID 为"+cacheName+ "的person 数据做了缓存");
});
return cacheManager;
}
}
package com.programb.example.config;
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
public class DBConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("ms.db.url"));
dataSource.setUser(env.getProperty("ms.db.username"));
dataSource.setPassword(env.getProperty("ms.db.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
package com.programb.example.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("com.programb.example.dao")
@EnableTransactionManagement
@ComponentScan
public class JpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.programb.example.bean");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
jpaProperties.put("hibernate.jdbc.batch_size",50);
factory.setJpaPropertyMap(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
package com.programb.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.programb.example.bean.Person;
import com.programb.example.service.PersonService;
@RestController
@RequestMapping(value = "/person")
public class CacheController {
@Autowired
private PersonService personService;
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Person put(Person person){
return personService.save(person);
}
@RequestMapping(value ="/{id}" ,method = RequestMethod.GET)
@ResponseBody
public Person cacheable( @PathVariable Long id){
return personService.findOne(id);
}
}
package com.programb.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.programb.example.bean.Person;
public interface PersonRepository extends JpaRepository<Person, Long> {
}
package com.programb.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.programb.example.bean.Person;
import com.programb.example.dao.PersonRepository;
import java.util.List;
@Service
public class DemoService {
@Autowired
private PersonRepository personRepository;
public List<Person> findAll() {
return personRepository.findAll();
}
}
package com.programb.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import com.programb.example.bean.Person;
import com.programb.example.dao.PersonRepository;
@Service
public class PersonService {
@Autowired
CacheManager cacheManager;
@Autowired
private PersonRepository personRepository;
public Person findOne(Long id) {
Person person = getCache(id, cacheManager);
if (person != null) {
System.out.println("从缓存中取出:" + person.toString());
} else {
person = personRepository.findOne(id);
System.out.println("从数据库中取出:" + person.toString());
}
return person;
}
public Person save(Person person) {
Person p = personRepository.save(person);
return p;
}
public Person getCache(Long id, CacheManager cacheManager) {
Cache cache = cacheManager.getCache(id.toString());
Cache.ValueWrapper valueWrapper = cache.get(id);
Person person = (Person) valueWrapper.get();
return person;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.programb</groupId>
<artifactId>springboot-Cache2</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.programb.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--缓存-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>