文档章节

一个SpringData JPA入门实例

蜡笔小小小新
 蜡笔小小小新
发布于 2016/07/10 22:41
字数 2979
阅读 996
收藏 12
点赞 0
评论 0

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那么灵活了。

 

© 著作权归作者所有

共有 人打赏支持
蜡笔小小小新
粉丝 32
博文 114
码字总数 75210
作品 0
深圳
后端工程师
恒宇少年/querydsl-chapter

#QueryDSL 简书相关系列文章源码 #一、环境配置 ###第一章:Maven环境下如何配置QueryDSL环境 #二、基础 ###第二章:整合QueryDSL与SpringDataJPA ###第三章:使用QueryDSL与SpringDataJPA完...

恒宇少年
04/19
0
0
第三章:使用QueryDSL与SpringDataJPA完成Update&Delete

我们上一章讲解了有关QueryDsl整合SpringDataJPA完成简单的单表条件查询,采用了两种模式进行查询一种是完全QueryDsl而另外一种则是整合的形式,既然单表的查询已经讲解接下来我们来看看Que...

恒宇少年
2017/07/05
0
0
第四十九章:SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗?

初升级版本,在已经使用的系统内还是存在一些兼容性的问题,有很多变化!!!也存在一些过时的方法、配置文件信息以及类,我们在之前版本的中可以使用抽象类来处理相关的配置,由于版本最低支...

恒宇少年
03/17
0
0
第四章:使用QueryDSL与SpringDataJPA实现多表关联查询

对于业务逻辑复制的系统来说都存在多表关联查询的情况,查询的返回对象内容也是根据具体业务来处理的,我们本章主要是针对多表关联根据条件查询后返回单表对象,在下一章我们就会针对多表查询...

恒宇少年
2017/07/09
0
0
第一章:Maven环境下如何配置QueryDSL环境

QueryDSL是一个通用的查询框架,框架的核心原则是创建安全类型的查询,开始QueryDSL仅支持Hibernate(HQL),在不断开源人士加入QueryDSL团队后,陆续发布了针对JPA,JDO,JDBC,Lucene,Hib...

恒宇少年
2017/07/01
0
0
第五十章:SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成

自从升级到了版本后集成作为缓存就更为简单了,我们只需要配置相关的链接信息以及使用注解开启缓存,这样我们就直接可以在项目内使用缓存相关的内容。 由于最近这段时间一直在研发公司的持久...

恒宇少年
04/15
0
0
恒宇少年/spring-boot-chapter

简书整套文档以及源码解析 专题 专题名称 专题描述 001 Spring Boot 核心技术 讲解SpringBoot一些企业级层面的核心组件 002 Spring Cloud 核心技术 对Spring Cloud核心技术全面讲解 003 Quer...

恒宇少年
04/19
0
0
第五十二章:基于SpringBoot2使用Rest访问MongoDB数据

在之前项目中我们想要读取内的内容需要使用来完成数据的,那如果我们想要通过的形式获取内的数据就更麻烦了,还需要自行去创建对应的控制器,然后使用从内读取出数据后返回给前端。 在上一章...

恒宇少年
04/22
0
0
Spring-data-jpa 让数据访问更简单、更优雅

Hibernate的基于Entity对象模型的数据ORM映射管理 门槛较高,深度应用比较复杂; 移植性好,兼容不同的数据库的操作; 数据访问层操作简单,基于HQL操作更加面向对象; 级联操作比较方便 My...

后海
2017/12/22
0
0
第五十一章:基于SpringBoot2 & MongoDB完成自动化集成

在企业级项目中一般用于存储文档信息、图片资源等,的内容完全是以 字符串的形式进行存储的,所以我们在获取数据时通过简单的 就可以完成与项目内的实体类转换,不过这个过程是自动的,不需要...

恒宇少年
04/16
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

【面试题】盲人坐飞机

有100位乘客乘坐飞机,其中有一位是盲人,每位乘客都按自己的座位号就坐。由于盲人看不见自己的座位号,所以他可能会坐错位置,而自己的座位被占的乘客会随便找个座位就坐。问所有乘客都坐对...

garkey
47分钟前
0
0
谈谈神秘的ES6——(二)ES6的变量

谈谈神秘的ES6——(二)ES6的变量 我们在《零基础入门JavaScript》的时候就说过,在ES5里,变量是有弊端的,我们先来回顾一下。 首先,在ES5中,我们所有的变量都是通过关键字var来定义的。...

JandenMa
今天
1
0
arts-week1

Algorithm 594. Longest Harmonious Subsequence - LeetCode 274. H-Index - LeetCode 219. Contains Duplicate II - LeetCode 217. Contains Duplicate - LeetCode 438. Find All Anagrams ......

yysue
今天
0
0
NNS拍卖合约

前言 关于NNS的介绍,这里就不多做描述,相关的信息可以查看NNS的白皮书http://doc.neons.name/zh_CN/latest/nns_background.html。 首先nns中使用的竞价货币是sgas,关于sgas介绍可以戳htt...

红烧飞鱼
今天
1
0
Java IO类库之管道流PipeInputStream与PipeOutputStream

一、java管道流介绍 在java多线程通信中管道通信是一种重要的通信方式,在java中我们通过配套使用管道输出流PipedOutputStream和管道输入流PipedInputStream完成线程间通信。多线程管道通信的...

老韭菜
今天
0
0
用Python绘制红楼梦词云图,竟然发现了这个!

Python在数据分析中越来越受欢迎,已经达到了统计学家对R的喜爱程度,Python的拥护者们当然不会落后于R,开发了一个个好玩的数据分析工具,下面我们来看看如何使用Python,来读红楼梦,绘制小...

猫咪编程
今天
1
0
Java中 发出请求获取别人的数据(阿里云 查询IP归属地)

1.效果 调用阿里云的接口 去定位IP地址 2. 代码 /** * 1. Java中远程调用方法 * http://localhost:8080/mavenssm20180519/invokingUrl.action * @Title: invokingUrl * @Description: * @ret......

Lucky_Me
今天
1
0
protobuf学习笔记

相关文档 Protocol buffers(protobuf)入门简介及性能分析 Protobuf学习 - 入门

OSC_fly
昨天
0
0
Mybaties入门介绍

Mybaties和Hibernate是我们在Java开发中应用的比较多的两个ORM框架。当然,目前Mybaties正在慢慢取代Hibernate,这是因为相比较Hibernate而言Mybaties性能更好,响应更快,更加灵活。我们在开...

王子城
昨天
2
0
编程学习笔记之python深入之装饰器案例及说明文档[图]

编程学习笔记之python深入之装饰器案例及说明文档[图] 装饰器即在不对一个函数体进行任何修改,以及不改变整体的原本意思的情况下,增加函数功能的新函数,因为这个新函数对旧函数进行了装饰...

原创小博客
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部