一个SpringData JPA入门实例
一个SpringData JPA入门实例
蜡笔小小小新 发表于2年前
一个SpringData JPA入门实例
  • 发表于 2年前
  • 阅读 974
  • 收藏 12
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

摘要: SpringData是Spring对JavaEE的持久层规范JPA的支持,和Hibernate一样,它的实现依靠HibernateProvider,可以大大提高系统持久层的开发效率,非常棒。

1.介绍

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

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

2.入门实例

2.1 创建项目

2.1.1 maven依赖

下面是pom.xml文件内容:

<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>SpringData</groupId>
	<artifactId>SpringData</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringData</name>
	<description />
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.2.1.Final</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>

		<!--spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.1.7.RELEASE</version>
		</dependency>

		<!--jsp和Servlet相关依赖 -->
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<version>3.1</version>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2.1.2 web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringData</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- Spring MVC核心控制器,如果不配置contextConfigLocation参数,那么默认就是/WEB-INF/下的springmvc-servlet.xml -->
	<servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
      	<param-name>contextConfigLocation</param-name>
      	<param-value>classpath*:spring-mvc.xml</param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- Spring监听器,监听ServletContext容器启动并注入ApplicationContext, Web应用中默认注入一个XmlWebApplicationContext -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- 框架配置文件位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:applicationContext-*.xml
	</param-value>
	</context-param>
</web-app>

2.1.3 SpringData JPA配置文件

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/data/jpa 
      http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

	<context:component-scan base-package="com.lin.springdata.dao" />
	<context:component-scan base-package="com.lin.springdata.service.impl" />

	<bean id="myEmf"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="com.lin.springdata.entities" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
		</property>
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!-- <prop key="hibernate.hbm2ddl.auto">create-drop</prop> 项目从新部署的时候会把表清空 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.ddl-auto">update</prop><!-- 自动创建表 -->
			</props>
		</property>
	</bean>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="myEmf" />
	</bean>
	<tx:annotation-driven />

	<bean id="persistenceExceptionTranslationPostProcessor"
		class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

	<jpa:repositories base-package="com.lin.springdata.dao"
		entity-manager-factory-ref="myEmf"
		transaction-manager-ref="transactionManager" />

</beans>

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<News, Integer> {
	
	public News readByTitle(String title);

}

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

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

<jpa:repositories base-package="com.lin.springdata.dao"
		entity-manager-factory-ref="myEmf"
		transaction-manager-ref="transactionManager" />

这样才能把这些接口注入到其他的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<News> 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<News> 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<News> newsList = newsService.listAll();
		
		Iterator<News> 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已经为我们自动创建了表并插入数据:

2.6 目录结构

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<News, Integer>,PagingAndSortingRepository扩展了CrudRepository接口。

调用PagingAndSortingRepository分页查询方法

@Transactional(readOnly=true)
	@Override
	public Iterable<News> 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<News> newsIterable = newsService.queryByPage(pageNumber);
		StringBuffer result = new StringBuffer();
		Iterator<News> 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<Comment> 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<Comment> getComments() {
		return comments;
	}

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

}

测试新增方法:

public String testOneToManyAdd()
	{
		News news = newsService.queryById(1);
		
		Collection<Comment> 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那么灵活了。

 

标签: Java Spring JPA
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 29
博文 112
码字总数 79661
×
蜡笔小小小新
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: