Spring-Data-JPA 定义实体类关系:一对多(增删改查)

SpringBoot 项目搭建参考

https://blog.csdn.net/zhouzhiwengang/article/details/108402298

源码文件夹(src)定义

实体对象和Dao层

package com.zzg.entity;

import java.util.List;
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.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

@Entity
@Table(name = "author")
@Data // 自动生成get、set、toString、equals方法
@AllArgsConstructor // 全参构造方法
@NoArgsConstructor // 无参构造方法
@Accessors(chain = true) // 链式编程
public class Author {
	@Id // 主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增长策略
    private Long id; //id
   
    @Column(nullable = false, length = 20)
    private String name;//姓名
    
    //@JoinColumn(name = "author_id")
    //级联保存、更新、删除、刷新;延迟加载。当删除用户,会级联删除该用户的所有文章
    //拥有mappedBy注解的实体类为关系被维护端
     //mappedBy="author"中的author是Article中的author属性
    @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
    private List
articleList;//文章列表 }
package com.zzg.entity;

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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;

@Entity
@Table(name = "article")
@Setter
@Getter
@EqualsAndHashCode// 自动生成get、set、toString、equals方法
@AllArgsConstructor // 全参构造方法
@NoArgsConstructor // 无参构造方法
@Accessors(chain = true) // 链式编程
public class Article {
	    @Id
	    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增长策略
	    private Long id;
	   
	    
	    @Column(nullable = false, length = 50) // 映射为字段,值不能为空
	    private String title;
	   
	    @Column(nullable = false) // 映射为字段,值不能为空
	    private String content;//文章全文内容
	    
	    //可选属性optional=false,表示author不能为空。删除文章,不影响用户
	    @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false)
	    @JoinColumn(name="author_id")//设置在article表中的关联字段(外键)
	    private Author author;//所属作者

		@Override
		public String toString() {
			// TODO Auto-generated method stub
			return "Article{ id='"+id+"'}";
		}    
}
package com.zzg.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.zzg.entity.Author;

@Repository
public interface AuthorRepository extends JpaRepository {
	Author findByName(String name);
}
package com.zzg.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.zzg.entity.Article;

@Repository
public interface ArticleRepository extends JpaRepository {

}

功能测试(test)定义:

package com.zzg.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.zzg.dao.ArticleRepository;
import com.zzg.dao.AuthorRepository;
import com.zzg.entity.Article;
import com.zzg.entity.Author;

/**
 * spring-data-jpa 一对多测试
 * @author zzg
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class OneToMany {
	@Autowired
	private ArticleRepository articleRepository;
	
	@Autowired
	private AuthorRepository authorRepository;
	
	@Test
	public void insertOneToMany(){
		Author author = new Author();
		author.setName("周晨曦");
		
		
		List
list = new ArrayList
(); for(int i =0; i<10; i++ ){ Article article = new Article(); article.setTitle("标题:" + i); article.setContent("内容:" + i); // 记住一定要添加关系实体对象,否在关联字段为null article.setAuthor(author); list.add(article); } author.setArticleList(list); authorRepository.save(author); } @Test public void selectOneToMany(){ Author author = authorRepository.findOne(10L); System.out.println("author=" + author); } @Test public void updateOneToMany(){ Author author = authorRepository.findOne(10L); List
articleList = author.getArticleList(); Article article = new Article(); article.setAuthor(author); articleList.add(article); authorRepository.save(author); } @Test public void deleteOneToMany(){ authorRepository.delete(10L); } }

增删改查效果截图:

新增:

Spring-Data-JPA 定义实体类关系:一对多(增删改查)_第1张图片

查询:

修改:

删除: 

Spring-Data-JPA 定义实体类关系:一对多(增删改查)_第2张图片

涉及表的数据库脚本:

CREATE TABLE `article`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `content` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `author_id` bigint(20) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `author_id`(`author_id`) USING BTREE,
  CONSTRAINT `author_id` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;


CREATE TABLE `author`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

 

你可能感兴趣的:(spring,Data,JPA)