一个SpringData JPA入门实例

为什么80%的码农都做不了架构师?>>>   hot3.png

1.介绍

这是SpringData JPA的文档,是了解SpringData最好的资料了。

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ 

2.入门实例

2.1 创建项目

2.1.1 maven依赖

下面是pom.xml文件内容:


	4.0.0
	SpringData
	SpringData
	0.0.1-SNAPSHOT
	war
	SpringData
	
	
		UTF-8
	

	

		
			org.hibernate
			hibernate-entitymanager
			4.2.1.Final
		

		
			mysql
			mysql-connector-java
			5.1.25
		

		
		
			org.springframework
			spring-core
			4.1.7.RELEASE
		
		
			org.springframework
			spring-beans
			4.1.7.RELEASE
		
		
			org.springframework
			spring-context
			4.1.7.RELEASE
		
		
			org.springframework
			spring-jdbc
			4.1.7.RELEASE
		
		
			org.springframework
			spring-tx
			4.1.7.RELEASE
		
		
			org.springframework
			spring-web
			4.1.7.RELEASE
		
		
			org.springframework
			spring-webmvc
			4.1.7.RELEASE
		
		
			org.springframework
			spring-test
			4.1.7.RELEASE
		

		
		
			taglibs
			standard
			1.1.2
		
		
			javax.servlet
			javax.servlet-api
			3.1.0
		

		
			junit
			junit
			4.11
			test
		

		
			org.springframework.data
			spring-data-jpa
			1.5.1.RELEASE
		
	

	
		
			
				maven-compiler-plugin
				2.3.2
				
					1.7
					1.7
				
			
			
				maven-war-plugin
				2.2
				
					3.1
					false
				
			
		
	

2.1.2 web.xml文件



  SpringData
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
	
        springmvc
        
            org.springframework.web.servlet.DispatcherServlet
        
        
      	contextConfigLocation
      	classpath*:spring-mvc.xml
    
        1
  
  
        springmvc
        /
  
  
  
	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		true
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	

	
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		org.springframework.web.util.IntrospectorCleanupListener
	
	
	
		contextConfigLocation
		classpath*:applicationContext-*.xml
	
	

2.1.3 SpringData JPA配置文件

我把文件命名为applicationContext-persistence.xml




	
	

	
		
		
		
			
		
		
			
				update
				
				org.hibernate.dialect.MySQL5Dialect
				update
			
		
	

	
		
		
		
		
	

	
		
	
	

	

	

SpringData的配置也可以已java代码的方式,google上面的很多教程很多是java代码的方式,都可以,看个人习惯。

2.2 model层

package com.lin.springdata.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TB_NEWS")
public class News implements Serializable {
	
	private static final long serialVersionUID = 4713558903448287254L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name = "title",nullable=false)
	private String title;
	
	@Column(name="content",nullable=false)
	private String content;
	
	@Column(name="createDate",nullable=false)
	private Date createDate;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", content=" + content
				+ ", createDate=" + createDate + "]";
	}

}

可以看到javax.persistance.*包里就是JPA规范的一些注解。

2.3 持久层

package com.lin.springdata.dao;

import org.springframework.data.repository.CrudRepository;

import com.lin.springdata.entities.News;

public interface NewsDAO extends CrudRepository {
	
	public News readByTitle(String title);

}

用SpringData开发的持久层接口只需要扩展Repository接口即可,并且Spring会代理该接口的实现,DAO层无需再实现该接口。

需要注意的是,DAO层的这些接口的包需要在配置文件里配置一下:

这样才能把这些接口注入到其他的bean中去。

2.4 业务逻辑层

2.4.1 业务层接口

package com.lin.springdata.service;

import com.lin.springdata.entities.News;

public interface NewsService{
	
	public void save(News news);
	
	public Iterable listAll();

}

2.4.2 业务逻辑组件

package com.lin.springdata.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lin.springdata.dao.NewsDAO;
import com.lin.springdata.entities.News;
import com.lin.springdata.service.NewsService;

@Service("newsService")
public class NewsServiceImpl implements NewsService {
	
	@Autowired
	protected NewsDAO newsDAO;

	@Transactional
	@Override
	public void save(News news) {
		
		if(news != null)
		{
			newsDAO.save(news);
		}
		
	}

	@Transactional
	@Override
	public Iterable listAll() {
		
		return newsDAO.findAll();
	}

}

2.5 测试

package test;

import java.util.Date;
import java.util.Iterator;

import javax.annotation.Resource;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.lin.springdata.entities.News;
import com.lin.springdata.service.NewsService;



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext-*.xml"})
public class Test {
	
	@Resource(name="newsService")
	private NewsService newsService;
	
	@org.junit.Test
	public void test()
	{
		News news = new News();
		news.setTitle("This is a test news");
		news.setContent("This is a test news.");
		news.setCreateDate(new Date());
		
		newsService.save(news);
		
		Iterable newsList = newsService.listAll();
		
		Iterator newsIterator = newsList.iterator();
		
		while(newsIterator.hasNext())
		{
			News temp = newsIterator.next();
			System.out.println(temp);
		}
	}

}

这个单元测试是成功的。但是在查数据库的时候发现并没有插入任何数据。这是什么原因呢?StackOverflow上面有人说是因为在Spring的单元测试中,在测试代码执行完毕后事务会回滚,所以在单元测试中的事务是没有提交的。可以先不使用事务。我这里是直接通过控制器来测试。下面是我用来测试的SpringMVC控制器:

package com.lin.springdata.controller;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lin.springdata.entities.News;
import com.lin.springdata.service.NewsService;

@Controller
public class TestController {
	
	@Resource(name="newsService")
	private NewsService newsService;
	
	@RequestMapping(value="/add",method=RequestMethod.GET)
	@ResponseBody
	public String testAdd()
	{
		News news = new News();
		news.setTitle("This is a test news");
		news.setContent("This is a test news.");
		news.setCreateDate(new Date());
		
		newsService.save(news);
		
		return "add news success.";
	}

}

测试结果:

这时在看看数据库,Springdata已经为我们自动创建了表并插入数据:

一个SpringData JPA入门实例_第1张图片

2.6 目录结构

一个SpringData JPA入门实例_第2张图片

2.7 怎么查询

由于Spring代理了DAO层接口,基本的crud方法可以直接调用,下面是用HQL查询的方式。

@Query("select n from News n where n.title=:title")
	public News readByTitle(@Param("title")String title);
	
	@Query("select n.title from News n where n.id=:id")
	public String readTitleById(@Param("id")int id);
	
	@Query("select n from News n where n.id=?1 and n.title=?2")
	public News readByIdAndTitle(int id,String title);

2.8 怎么分页查询

修改NewsDAO接口

public interface NewsDAO extends PagingAndSortingRepository,PagingAndSortingRepository扩展了CrudRepository接口。

调用PagingAndSortingRepository分页查询方法

@Transactional(readOnly=true)
	@Override
	public Iterable queryByPage(int pageNumber) {
		
		PageRequest pageRequest = new PageRequest(pageNumber - 1, PAGE_SIZE,Sort.Direction.DESC, "id");
		
		return newsDAO.findAll(pageRequest);
	}

PageRequest的参数说明:

1:页码    2:每页显示条数    3:升序降序的标记    4:升序降序根据那个字段来排序,可以是数组

测试:

@RequestMapping(value="/news/page/{page}")
	@ResponseBody
	public String testPage(@PathVariable("page")int pageNumber)
	{
		Iterable newsIterable = newsService.queryByPage(pageNumber);
		StringBuffer result = new StringBuffer();
		Iterator newsList = newsIterable.iterator();
		
		while(newsList.hasNext())
		{
			result.append(newsList.next().toString()+"\n");
		}
		
		return result.toString();
	}

2.9 怎么更新数据

和hibernate不一样,Repository没有update或saveOrUpdate方法,其实,这两个方法的作用都是把实体对象的状态变成持久态,那么在SpringDataJPA中,同样只要把对象在更新后变成持久态就可以了,因此save方法可以用于更新。或则使用@Modifying+@Query执行HQL来更新。

@Modifying
	@Query("update News n set n.title=:title,n.content=:content,createDate=:updateDate where n.id=:id")
	public void update(@Param("id")int newsId,@Param("title")String title,@Param("content")String content,@Param("updateDate")Date updateDate);

2.10 关联

2.10.1 OneToOne

之前我们有了News类,现在新加一个类NewsDetails,它和News是一对一的关系,修改News

package com.lin.springdata.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="TB_NEWS")
public class News implements Serializable {
	
	private static final long serialVersionUID = 4713558903448287254L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name = "title",nullable=false)
	private String title;
	
	@Column(name="content",nullable=false)
	private String content;
	
	@Column(name="createDate",nullable=false)
	private Date createDate;
	
	@OneToOne(cascade=CascadeType.ALL,mappedBy="news")//mapperBy的值和NewsDeetail中News的变量名一致
	private NewsDetails newsDetails;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public NewsDetails getNewsDetails() {
		return newsDetails;
	}

	public void setNewsDetails(NewsDetails newsDetails) {
		this.newsDetails = newsDetails;
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", content=" + content
				+ ", createDate=" + createDate + ", newsDetails=" + newsDetails
				+ "]";
	}

}

NewsDetails类:

package com.lin.springdata.entities;

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.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Table(name="TB_NEWS_DETAILS")
@Entity
public class NewsDetails implements Serializable {

	private static final long serialVersionUID = -2559429260718718580L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name="details",nullable=false)
	private String details;
	
	@OneToOne
	@JoinColumn(name="news_id")
	private News news;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	@Override
	public String toString() {
		return "NewsDetails [id=" + id + ", details=" + details + ", news="
				+ news + "]";
	}

}

2.10 关联关系

2.10.1 OneToOne

现在News和NewsDetails是一对一关系,NewsDetails的表的外键是News表的主键。修改News类增加NewsDetails类。

News:

package com.lin.springdata.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@Table(name="TB_NEWS")
public class News implements Serializable {
	
	private static final long serialVersionUID = 4713558903448287254L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name = "title",nullable=false)
	private String title;
	
	@Column(name="content",nullable=false)
	private String content;
	
	@Column(name="createDate",nullable=false)
	private Date createDate;
	
	@OneToOne(fetch=FetchType.LAZY, mappedBy="news",cascade=CascadeType.ALL)
	private NewsDetails newsDetails;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@OneToOne(cascade=CascadeType.ALL,mappedBy="news")
	public NewsDetails getNewsDetails() {
		return newsDetails;
	}

	public void setNewsDetails(NewsDetails newsDetails) {
		this.newsDetails = newsDetails;
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", content=" + content
				+ ", createDate=" + createDate + ", newsDetails=" + newsDetails
				+ "]";
	}

}

NewsDetails:

package com.lin.springdata.entities;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Table(name="TB_NEWS_DETAILS")
@Entity
public class NewsDetails implements Serializable {

	private static final long serialVersionUID = -2559429260718718580L;
	
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name="details",nullable=false)
	private String details;
	
	@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE},fetch=FetchType.LAZY)
	@JoinColumn(name="news_id")
	private News news;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	@Override
	public String toString() {
		return "NewsDetails [id=" + id + ", details=" + details + "]";
	}

}

持久化之前限设置news对象和newsDetails对象关联

public String testOneToOneAdd()
	{
		News news = newsService.queryById(1);
		NewsDetails newsDetails = new NewsDetails();
		newsDetails.setDetails("this is a news details.");
		System.out.println(news);
		/**
		 * 关联
		 */
		news.setNewsDetails(newsDetails);
		newsDetails.setNews(news);
		
		newsService.save(news);
		
		return "success";
	}

查询,略。

2.10.2 OneToMany

现在我们再写一个类Comment,它和News是多对一的关系。

Comment:

package com.lin.springdata.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Table(name="TB_COMMENT")
@Entity
public class Comment implements Serializable {

	private static final long serialVersionUID = -4681300680650337995L;
	
	@Id
    @GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name = "content",nullable=false)
	private String content;
	
	@Column(name = "commentDate",nullable=false)
	private Date commentDate;
	
	@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="news_id")
	private News news;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getCommentDate() {
		return commentDate;
	}

	public void setCommentDate(Date commentDate) {
		this.commentDate = commentDate;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

}

修改News:

package com.lin.springdata.entities;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="TB_NEWS")
public class News implements Serializable {
	
	private static final long serialVersionUID = 4713558903448287254L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(name = "title",nullable=false)
	private String title;
	
	@Column(name="content",nullable=false)
	private String content;
	
	@Column(name="createDate",nullable=false)
	private Date createDate;
	
	@OneToOne(fetch=FetchType.LAZY, mappedBy="news",cascade=CascadeType.ALL)
	private NewsDetails newsDetails;
	
	@OneToMany(fetch = FetchType.EAGER, mappedBy = "news", cascade = CascadeType.ALL)
	private Collection comments = new LinkedList<>();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	
	public NewsDetails getNewsDetails() {
		return newsDetails;
	}

	public void setNewsDetails(NewsDetails newsDetails) {
		this.newsDetails = newsDetails;
	}

	public Collection getComments() {
		return comments;
	}

	public void setComments(Collection comments) {
		this.comments = comments;
	}

}

测试新增方法:

public String testOneToManyAdd()
	{
		News news = newsService.queryById(1);
		
		Collection comments = new ArrayList<>();
		for(int i=0;i<10;i++)
		{
			Comment comment = new Comment();
			comment.setContent("comment"+i);
			comment.setCommentDate(new Date());
			comment.setNews(news);
			
			comments.add(comment);
		}
		news.setComments(comments);
		
		newsService.save(news);
		
		return "success";
	}

查询,略。

3.总结

JPA作为JavaEE规范之一,它对应用持久层API进行了统一,使得应用尽可能不衣赖哪种数据库,移植性较好,难度和hibernate差不多,较难掌握,相比MyBatis入门也需要更多的时间,不过开发效率更快。当然肯定没有MyBatis和直接JDBC那么灵活了。

 

转载于:https://my.oschina.net/ChiLin/blog/709340

你可能感兴趣的:(一个SpringData JPA入门实例)