JPA感觉像是Hibernate的注解实现,不再需要配置hibernate的映射文件,并且也实现了和更新了hibernate的缓存机制。比如jpa的一些增删该查的方法,并不是直接去curd的数据库,而是要经过一下缓存。调用flush的时候,才再次与数据库同步。废话少说上代码
目录结构
Spring配置文件applicationContext.xml:
org.hibernate.cfg.ImprovedNamingStrategy
true
true
update
org.hibernate.dialect.MySQL5InnoDBDialect
true
true
org.hibernate.cache.ehcache.EhCacheRegionFactory
SpringMVC配置文件spring-mvc.xml:
数据库配置文件jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/user?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username=root
jdbc.password=upassword
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
BoneCP.idleConnectionTestPeriod=60
BoneCP.idleMaxAge=60
BoneCP.maxConnectionsPerPartition=5
BoneCP.minConnectionsPerPartition=1
BoneCP.partitionCount=3
BoneCP.acquireIncrement=2
BoneCP.statementsCacheSize=0
BoneCP.releaseHelperThreads=3
web配置文件web.xml:
Archetype Created Web Application
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
hiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
hiddenHttpMethodFilter
/*
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
dispatcher
/
DruidStatView
com.alibaba.druid.support.http.StatViewServlet
DruidStatView
/druid/*
controller:
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/saveUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public String saveUser(@RequestBody User user){
return userService.add(user);
}
@RequestMapping(value = "/saveUser/{account}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public String add(@PathVariable String account){
return userService.addUser(account);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public User add(@PathVariable Long id){
return userService.getOneUser(id);
}
@RequestMapping(value = "/userList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
public List userList(){
return userService.getAllUser();
}
}
entity:
package com.lwl.spring_JPA.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "tb_user")
@NamedQueries({
@NamedQuery(name="findAllUser",query="from User"),
@NamedQuery(name="findUserWithId",query="SELECT u FROM User u WHERE u.id = ?1"),
@NamedQuery(name="findUserWithName",query="SELECT u FROM User u WHERE u.username = :username"),
@NamedQuery(name="deleteAllUser",query="delete FROM User")
})
public class User implements Serializable {
private static final long serialVersionUID = 7419229779731522702L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name="userName",length = 64)
private String username;
@Column(length = 64)
private String account;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "id="+id+",username="+username+",account="+account;
}
}
dao:
package com.lwl.spring_JPA.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "tb_user")
@NamedQueries({
@NamedQuery(name="findAllUser",query="from User"),
@NamedQuery(name="findUserWithId",query="SELECT u FROM User u WHERE u.id = ?1"),
@NamedQuery(name="findUserWithName",query="SELECT u FROM User u WHERE u.username = :username"),
@NamedQuery(name="deleteAllUser",query="delete FROM User")
})
public class User implements Serializable {
private static final long serialVersionUID = 7419229779731522702L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name="userName",length = 64)
private String username;
@Column(length = 64)
private String account;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "id="+id+",username="+username+",account="+account;
}
}
daoImpl:
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager entityManager;
@Override
public void deleteAllInBatch() {
entityManager.detach(User.class);
}
@Override
public void deleteInBatch(Iterable arg0) {
if(arg0 != null) {
Iterator it = arg0.iterator();
while(it.hasNext()) {
entityManager.remove(it.next());
}
}
}
@Override
public List findAll() {
List ulist = entityManager.createNamedQuery("findAllUser").getResultList();
for(User u :ulist) {
System.out.println(u);
}
return ulist;
}
@Override
public List findAll(Sort arg0) {
Iterator it = arg0.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
List ulist = entityManager.createNamedQuery("from user ").getResultList();
return ulist;
}
@Override
public List findAll(Iterable arg0) {
return null;
}
@Override
public void flush() {
entityManager.flush();
}
@Override
public User getOne(Long arg0) {
return entityManager.find(User.class, arg0);
}
@Override
public List save(Iterable arg0) {
List list = new ArrayList<>();
Iterator it = arg0.iterator();
while(it.hasNext()) {
S s = it.next();
entityManager.persist(s);
list.add(s);
}
return list;
}
@Override
public S saveAndFlush(S arg0) {
entityManager.persist(arg0);
entityManager.flush();
return arg0;
}
@Override
public Page findAll(Pageable arg0) {
return null;
}
@Override
public long count() {
List ulist = entityManager.createNamedQuery("findAllUser", User.class).getResultList();
return ulist.size();
}
@Override
public void delete(Long arg0) {
entityManager.remove(entityManager.find(User.class, arg0));
}
@Override
public void delete(User arg0) {
entityManager.remove(arg0);
}
@Override
public void delete(Iterable extends User> arg0) {
Iterator it = arg0.iterator();
while(it.hasNext()) {
entityManager.remove(it.next());
}
}
@Override
public void deleteAll() {
int count= entityManager.createNamedQuery("deleteAllUser").executeUpdate();
System.out.println(count);
}
@Override
public boolean exists(Long arg0) {
return entityManager.contains(entityManager.find(User.class, arg0));
}
@Override
public User findOne(Long arg0) {
return entityManager.find(User.class, arg0);
}
@Override
public S save(S arg0) {
entityManager.persist(arg0);
return arg0;
}
}
service:
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
public String add(User user){
userDao.save(user);
return "添加成功!";
}
public String addUser(String account){
User user = new User();
user.setAccount(account);
userDao.save(user);
return "添加成功!";
}
public User getOneUser(Long id){
return userDao.findOne(id);
}
public List getAllUser(){
return userDao.findAll();
}
}
访问:http://localhost:8080/user/userList查看数据