├── .gitignore ├── .springBeans ├── README.md ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ ├── App.java │ │ │ ├── common │ │ │ ├── BoardArticle.java │ │ │ ├── BoardArticleRepository.java │ │ │ ├── Comment.java │ │ │ ├── CommentRepository.java │ │ │ ├── CommonBoardArticleController.java │ │ │ ├── Tags.java │ │ │ ├── User.java │ │ │ └── UserRepository.java │ │ │ ├── etc │ │ │ └── validation │ │ │ │ ├── DressOrder.java │ │ │ │ ├── DressOrderRepository.java │ │ │ │ └── ValidationController.java │ │ │ ├── mapping │ │ │ ├── collection │ │ │ │ └── MapStudent.java │ │ │ ├── compoundkey │ │ │ │ ├── ComposedIdKey.java │ │ │ │ ├── CompoundKeyController.java │ │ │ │ ├── PeopleManagement.java │ │ │ │ └── PeopleManagementRepository.java │ │ │ ├── embedded │ │ │ │ ├── EmbeddedController.java │ │ │ │ ├── HumanBody.java │ │ │ │ ├── HumanBodyRepository.java │ │ │ │ └── Leg.java │ │ │ ├── inheritance │ │ │ │ ├── join │ │ │ │ │ ├── BaseBallPlayer.java │ │ │ │ │ ├── BaseBallPlayerRepository.java │ │ │ │ │ ├── HanWhaPlayer.java │ │ │ │ │ ├── InheritanceJoinController.java │ │ │ │ │ └── SkPlayer.java │ │ │ │ ├── perclass │ │ │ │ │ ├── Module.java │ │ │ │ │ ├── PrivateProject.java │ │ │ │ │ ├── Project.java │ │ │ │ │ ├── ProjectRepository.java │ │ │ │ │ └── inheritancePerClassController.java │ │ │ │ └── singletable │ │ │ │ │ ├── Animal.java │ │ │ │ │ ├── AnimalRepository.java │ │ │ │ │ ├── Bird.java │ │ │ │ │ ├── InheritanceSingleController.java │ │ │ │ │ └── Lion.java │ │ │ ├── mappedsuperclass │ │ │ │ ├── BaseEntity.java │ │ │ │ ├── MappedController.java │ │ │ │ ├── MappedSuperRepository.java │ │ │ │ └── MappedSupper.java │ │ │ └── secondary │ │ │ │ ├── SecondaryController.java │ │ │ │ ├── SecondaryRepository.java │ │ │ │ └── Secondarymaster.java │ │ │ ├── query │ │ │ └── jpql │ │ │ │ └── JPQLController.java │ │ │ └── r_mapping │ │ │ ├── justone │ │ │ ├── JustOne.java │ │ │ ├── JustOneController.java │ │ │ ├── JustOneEnum.java │ │ │ └── JustOneRepository.java │ │ │ ├── manytomany │ │ │ ├── Book.java │ │ │ ├── BookRepository.java │ │ │ ├── Category.java │ │ │ ├── CategoryRepository.java │ │ │ └── ManyToManyController.java │ │ │ ├── onetomany │ │ │ ├── OnetoManyController.java │ │ │ ├── Student.java │ │ │ ├── University.java │ │ │ └── UniversityRepository.java │ │ │ └── onetoone │ │ │ ├── Member.java │ │ │ ├── MemberDetail.java │ │ │ ├── MemberRepository.java │ │ │ └── OnetoOneController.java │ ├── resources │ │ ├── application.yml │ │ ├── db-config.yml │ │ ├── locale │ │ │ └── messages_kr_KR.xml │ │ ├── rebel.xml │ │ └── static │ │ │ └── images │ │ │ ├── inheritancesingle.png │ │ │ ├── inheritancesingle2.png │ │ │ ├── inheritancesingle3.png │ │ │ ├── justone.png │ │ │ ├── manytomany.png │ │ │ ├── manytomany2.png │ │ │ ├── manytomany3.png │ │ │ ├── mappedsupper.png │ │ │ ├── mappedsupper2.png │ │ │ ├── mappedsupper3.png │ │ │ ├── me.jpg │ │ │ ├── onetomany.png │ │ │ ├── onetomany2.png │ │ │ ├── onetomany3.png │ │ │ ├── onetoone.png │ │ │ ├── onetoone2.png │ │ │ ├── onetoone3.png │ │ │ ├── secondary.png │ │ │ ├── secondary2.png │ │ │ └── secondary3.png │ └── webapp │ │ └── WEB-INF │ │ ├── views │ │ └── index.jsp │ │ └── web.xml └── test │ └── java │ └── com │ └── example │ └── mapping │ ├── justone │ └── JustOneRepositoryTest.java │ ├── manytomany │ └── BookRepositoryTest.java │ ├── onetoone │ └── MemberRepositoryTest.java │ └── secondary │ └── SecondarymasterTest.java └── target └── m2e-wtp └── web-resources └── META-INF ├── MANIFEST.MF └── maven └── com.example └── LearnSpringDataJpa ├── pom.properties └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | #!! ERROR: jav is undefined. Use list command to see defined gitignore types !!# 4 | 5 | ### Java ### 6 | *.class 7 | 8 | # Mobile Tools for Java (J2ME) 9 | .mtj.tmp/ 10 | 11 | # Package Files # 12 | *.jar 13 | *.war 14 | *.ear 15 | 16 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 17 | hs_err_pid* 18 | 19 | 20 | ### Eclipse ### 21 | *.pydevproject 22 | .metadata 23 | .gradle 24 | bin/ 25 | tmp/ 26 | *.tmp 27 | *.bak 28 | *.swp 29 | *~.nib 30 | local.properties 31 | .settings/ 32 | .loadpath 33 | 34 | # Eclipse Core 35 | .project 36 | 37 | # External tool builders 38 | .externalToolBuilders/ 39 | 40 | # Locally stored "Eclipse launch configurations" 41 | *.launch 42 | 43 | # CDT-specific 44 | .cproject 45 | 46 | # JDT-specific (Eclipse Java Development Tools) 47 | .classpath 48 | 49 | # PDT-specific 50 | .buildpath 51 | 52 | # sbteclipse plugin 53 | .target 54 | 55 | # TeXlipse plugin 56 | .texlipse 57 | /target/ 58 | -------------------------------------------------------------------------------- /.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # learnspringdatajpa 2 | 개인적 정리하는김에 스터디구성원들과 나누기 위해서 스프링 data jpa 간단히 정리해봅니다. 3 | http://www.slideshare.net/meadunhansa/spring-data-jpa-46105441 4 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.example 5 | LearnSpringDataJpa 6 | jar 7 | 0.0.1-SNAPSHOT 8 | Learn Jpa and Spring data jpa 9 | Jpa Study 10 | http://maven.apache.org 11 | 12 | 13 | UTF-8 14 | com.example.App 15 | 1.8 16 | 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-parent 22 | 1.2.5.RELEASE 23 | 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.16.10 40 | 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-data-jpa 46 | 47 | 48 | org.apache.tomcat.embed 49 | tomcat-embed-websocket 50 | provided 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-tomcat 56 | provided 57 | 58 | 59 | 60 | org.apache.tomcat.embed 61 | tomcat-embed-jasper 62 | provided 63 | 64 | 65 | 66 | javax.servlet 67 | jstl 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-test 76 | test 77 | 78 | 79 | 80 | 81 | 82 | 83 | joda-time 84 | joda-time 85 | 2.5 86 | 87 | 88 | joda-time 89 | joda-time-jsptags 90 | 1.1.1 91 | 92 | 93 | org.jadira.usertype 94 | usertype.spi 95 | 3.0.0.GA 96 | 97 | 98 | 99 | org.jadira.usertype 100 | usertype.core 101 | 3.0.0.GA 102 | 103 | 104 | 105 | 106 | 107 | mysql 108 | mysql-connector-java 109 | 110 | 111 | com.h2database 112 | h2 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | LearnSpringDataJpa 123 | 124 | 125 | 126 | org.apache.maven.plugins 127 | maven-compiler-plugin 128 | 129 | 1.8 130 | 1.8 131 | 132 | 133 | 134 | org.springframework.boot 135 | spring-boot-maven-plugin 136 | 137 | exec 138 | 139 | 140 | 141 | maven-jar-plugin 142 | 143 | 144 | exec 145 | package 146 | 147 | jar 148 | 149 | 150 | exec 151 | 152 | 153 | 154 | package 155 | 156 | jar 157 | 158 | 159 | 160 | true 161 | 162 | application.yml 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /src/main/java/com/example/App.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | import javax.persistence.EntityManagerFactory; 9 | 10 | import org.springframework.boot.SpringApplication; 11 | import org.springframework.boot.autoconfigure.SpringBootApplication; 12 | import org.springframework.context.MessageSource; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; 15 | import org.springframework.context.support.ReloadableResourceBundleMessageSource; 16 | import org.springframework.context.support.ResourceBundleMessageSource; 17 | import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; 18 | import org.springframework.stereotype.Controller; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | 21 | @SpringBootApplication 22 | @Controller 23 | public class App { 24 | 25 | public static final String returnPath="redirect:/"; 26 | public static final String index="index"; 27 | 28 | @RequestMapping("/") 29 | public String home() { 30 | return App.index; 31 | } 32 | 33 | public static void main(String[] args) throws Exception { 34 | SpringApplication.run(App.class, customizeArgs(args)); 35 | } 36 | 37 | // reference link 38 | // https://github.com/sbcoba/spring-camp-2015-sample/blob/master/spring-camp-env-boot-yaml-sample/src/main/java/com/springcamp/env/SampleProfileApplication.java 39 | private static String[] customizeArgs(String[] args) { 40 | List argList = new ArrayList(Arrays.asList(args)); 41 | argList.add("--spring.config.location=" + 42 | "classpath:db-config.yml"); 43 | String[] mergeArgs = argList.toArray(new String[]{}); 44 | return mergeArgs; 45 | } 46 | 47 | 48 | // To get SessionFactory in Spring 49 | // https://mdeinum.wordpress.com/2015/07/01/spring-framework-hidden-gems/ 50 | @Bean 51 | public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf){ 52 | HibernateJpaSessionFactoryBean jssfb = new HibernateJpaSessionFactoryBean(); 53 | jssfb.setEntityManagerFactory(emf); 54 | return jssfb; 55 | } 56 | 57 | //message 58 | private static final String MESSAGE_SOURCE_BASE_NAME = "locale"; 59 | 60 | @Bean 61 | public MessageSource messageSource() { 62 | ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 63 | messageSource.setBasename(MESSAGE_SOURCE_BASE_NAME); 64 | messageSource.setDefaultEncoding("UTF-8"); 65 | messageSource.setUseCodeAsDefaultMessage(true); 66 | return messageSource; 67 | } 68 | 69 | @Bean 70 | public PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { 71 | return new PropertySourcesPlaceholderConfigurer(); 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/com/example/common/BoardArticle.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.FetchType; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.Id; 11 | import javax.persistence.JoinColumn; 12 | import javax.persistence.ManyToOne; 13 | import javax.persistence.OneToMany; 14 | import javax.persistence.PrePersist; 15 | import javax.persistence.PreUpdate; 16 | import javax.persistence.Version; 17 | 18 | import org.hibernate.annotations.Type; 19 | import org.joda.time.DateTime; 20 | 21 | import com.example.mapping.mappedsuperclass.BaseEntity; 22 | 23 | @Entity 24 | public class BoardArticle{ 25 | 26 | @Id 27 | @GeneratedValue 28 | private Long id; 29 | 30 | private String title; 31 | 32 | private String content; 33 | 34 | @Column(name="numread") 35 | private int numRead; 36 | 37 | @Column(name = "creation_time", nullable = false) 38 | @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") 39 | private DateTime creationTime; 40 | 41 | @Column(name = "modification_time", nullable = false) 42 | @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") 43 | private DateTime modificationTime; 44 | 45 | @Version 46 | private long version; 47 | 48 | // 주의... cascade 타입 주의. 토이프로그램임. 49 | @ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY) 50 | @JoinColumn(name="user_id") 51 | private User user; 52 | 53 | 54 | @OneToMany(targetEntity=Comment.class, 55 | mappedBy="article", 56 | cascade=CascadeType.ALL, 57 | fetch=FetchType.LAZY 58 | ) 59 | private List comments; 60 | 61 | 62 | 63 | public BoardArticle() { 64 | } 65 | public BoardArticle(Long id){ 66 | this.id =id; 67 | } 68 | 69 | public BoardArticle(String nick, String title, String content) { 70 | super(); 71 | this.title = title; 72 | this.content = content; 73 | } 74 | 75 | 76 | 77 | public Long getId() 78 | { 79 | return id; 80 | } 81 | 82 | public void setId(Long id) 83 | { 84 | this.id = id; 85 | } 86 | 87 | public String getTitle() 88 | { 89 | return title; 90 | } 91 | 92 | public void setTitle(String title) 93 | { 94 | this.title = title; 95 | } 96 | 97 | public String getContent() 98 | { 99 | return content; 100 | } 101 | 102 | public void setContent(String content) 103 | { 104 | this.content = content; 105 | } 106 | 107 | public int getNumRead() 108 | { 109 | return numRead; 110 | } 111 | 112 | public void setNumRead(int numRead) 113 | { 114 | this.numRead = numRead; 115 | } 116 | 117 | public DateTime getCreationTime() 118 | { 119 | return creationTime; 120 | } 121 | 122 | public void setCreationTime(DateTime creationTime) 123 | { 124 | this.creationTime = creationTime; 125 | } 126 | 127 | public DateTime getModificationTime() 128 | { 129 | return modificationTime; 130 | } 131 | 132 | public void setModificationTime(DateTime modificationTime) 133 | { 134 | this.modificationTime = modificationTime; 135 | } 136 | 137 | public long getVersion() 138 | { 139 | return version; 140 | } 141 | 142 | public void setVersion(long version) 143 | { 144 | this.version = version; 145 | } 146 | 147 | public User getUser() 148 | { 149 | return user; 150 | } 151 | 152 | public void setUser(User user) 153 | { 154 | this.user = user; 155 | } 156 | 157 | 158 | 159 | 160 | 161 | public List getComments() 162 | { 163 | return comments; 164 | } 165 | 166 | public void setComments(List comments) 167 | { 168 | this.comments = comments; 169 | } 170 | 171 | @PrePersist 172 | public void prePersist() { 173 | DateTime now = DateTime.now(); 174 | this.creationTime = now; 175 | this.modificationTime = now; 176 | } 177 | 178 | @PreUpdate 179 | public void preUpdate() { 180 | this.modificationTime = DateTime.now(); 181 | } 182 | 183 | @Override 184 | public String toString() 185 | { 186 | return "BoardArticle [id=" + id + ", title=" + title 187 | + ", content=" + content + ", numRead=" + numRead 188 | + ", creationTime=" + creationTime + ", modificationTime=" 189 | + modificationTime + ", version=" + version + "]
" 190 | + "
"; 191 | } 192 | 193 | 194 | public String toStringAll() 195 | { 196 | return "BoardArticle [id=" + id + ", title=" + title 197 | + ", content=" + content + ", numRead=" + numRead 198 | + ", creationTime=" + creationTime + ", modificationTime=" 199 | + modificationTime + ", version=" + version + "]
"+ getComments() +"
" 200 | + getUser() +"
" 201 | + "
댓글작성 :
" 202 | + "사용자 정보: " 203 | + "" 204 | +"
"; 205 | } 206 | 207 | 208 | } 209 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/BoardArticleRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.Modifying; 5 | import org.springframework.data.jpa.repository.Query; 6 | 7 | public interface BoardArticleRepository extends JpaRepository { 8 | 9 | @Modifying(clearAutomatically=true) 10 | @Query("update BoardArticle t set t.numRead = t.numRead + 1 where t.id = ?1") 11 | public int plusNumRead(Long id); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/Comment.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import javax.persistence.CascadeType; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.ManyToOne; 9 | 10 | @Entity 11 | public class Comment { 12 | 13 | @Id 14 | @GeneratedValue 15 | private Long id; 16 | private String reply; 17 | 18 | private int numlike; 19 | 20 | 21 | @ManyToOne 22 | @JoinColumn(name="article_id") 23 | private BoardArticle article; 24 | 25 | /*@ManyToOne 26 | @JoinColumn(name="user_id") 27 | private User user;*/ 28 | 29 | 30 | 31 | public Long getId() 32 | { 33 | return id; 34 | } 35 | 36 | public void setId(Long id) 37 | { 38 | this.id = id; 39 | } 40 | 41 | public String getComment() 42 | { 43 | return reply; 44 | } 45 | 46 | public void setComment(String comment) 47 | { 48 | this.reply = comment; 49 | } 50 | 51 | public int getNumlike() 52 | { 53 | return numlike; 54 | } 55 | 56 | public void setNumlike(int numlike) 57 | { 58 | this.numlike = numlike; 59 | } 60 | 61 | public BoardArticle getArticle() 62 | { 63 | return article; 64 | } 65 | 66 | public void setArticle(BoardArticle article) 67 | { 68 | this.article = article; 69 | } 70 | 71 | 72 | 73 | public String getReply() 74 | { 75 | return reply; 76 | } 77 | 78 | public void setReply(String reply) 79 | { 80 | this.reply = reply; 81 | } 82 | 83 | @Override 84 | public String toString() 85 | { 86 | return "Comment [id=" + id + ", comment=" + reply + ", numlike=" 87 | + numlike + "]
"; 88 | } 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface CommentRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/CommonBoardArticleController.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import org.hibernate.Hibernate; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.Model; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | import com.example.App; 12 | 13 | @Controller 14 | public class CommonBoardArticleController { 15 | 16 | @Autowired BoardArticleRepository repoBoard; 17 | @Autowired CommentRepository repoComment; 18 | @Autowired UserRepository repoUser; 19 | 20 | @RequestMapping(value="/commonBoard", method=RequestMethod.GET) 21 | public String commonBoardGet(Model model){ 22 | model.addAttribute("data", repoBoard.findAll()); 23 | return App.index; 24 | } 25 | 26 | @RequestMapping(value="/commonBoard", method=RequestMethod.POST) 27 | public String commonBoard(Model model, BoardArticle article, User user) 28 | { 29 | System.out.println(user); 30 | System.out.println(article); 31 | article.setUser(user); 32 | 33 | repoBoard.save(article); 34 | Hibernate.initialize(article); 35 | model.addAttribute("data", repoBoard.findAll()); 36 | return App.index; 37 | } 38 | 39 | 40 | @RequestMapping(value="/commonBoard/{id}", method=RequestMethod.GET) 41 | public String commonBoardgetId(Model model, @PathVariable Long id) 42 | { 43 | BoardArticle findOne = repoBoard.findOne(id); 44 | model.addAttribute("data", findOne.toStringAll()); 45 | return App.index; 46 | } 47 | 48 | @RequestMapping(value="/commonBoard/{articleid}", method=RequestMethod.POST) 49 | public String command(Model model,BoardArticle article, Comment comment, @PathVariable Long articleid){ 50 | System.out.println(comment); 51 | comment.setArticle(new BoardArticle(articleid)); 52 | System.out.println(comment); 53 | repoComment.save(comment); 54 | 55 | BoardArticle findOne = repoBoard.findOne(articleid); 56 | model.addAttribute("data", findOne.toStringAll()); 57 | return App.index; 58 | } 59 | 60 | 61 | @RequestMapping("/user/{userid}") 62 | public String userGet (Model model, @PathVariable Long userid) 63 | { 64 | model.addAttribute("data", repoUser.findOne(userid)); 65 | return App.index; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/Tags.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | 7 | @Entity 8 | public class Tags { 9 | 10 | 11 | @Id 12 | @GeneratedValue 13 | private Long id; 14 | 15 | private String nametag; 16 | 17 | 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/User.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Entity; 7 | import javax.persistence.FetchType; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.persistence.OneToMany; 11 | 12 | @Entity 13 | public class User { 14 | 15 | @Id 16 | @GeneratedValue 17 | private Long id; 18 | 19 | private String nick; 20 | 21 | private int age; 22 | 23 | @OneToMany( 24 | targetEntity=BoardArticle.class, 25 | mappedBy="user", 26 | cascade=CascadeType.ALL, 27 | fetch=FetchType.LAZY 28 | ) 29 | private List articles; 30 | 31 | 32 | 33 | 34 | 35 | public Long getId() 36 | { 37 | return id; 38 | } 39 | 40 | public void setId(Long id) 41 | { 42 | this.id = id; 43 | } 44 | 45 | public String getNick() 46 | { 47 | return nick; 48 | } 49 | 50 | public void setNick(String nick) 51 | { 52 | this.nick = nick; 53 | } 54 | 55 | public int getAge() 56 | { 57 | return age; 58 | } 59 | 60 | public void setAge(int age) 61 | { 62 | this.age = age; 63 | } 64 | 65 | public List getArticles() 66 | { 67 | return articles; 68 | } 69 | 70 | public void setArticles(List articles) 71 | { 72 | this.articles = articles; 73 | } 74 | 75 | 76 | 77 | @Override 78 | public String toString() 79 | { 80 | return "User [id=" + id + ", nick=" + nick + ", age=" + age 81 | + "]"; 82 | } 83 | 84 | public String toStringAll(){ 85 | return ""; 86 | } 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/example/common/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.common; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface UserRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/etc/validation/DressOrder.java: -------------------------------------------------------------------------------- 1 | package com.example.etc.validation; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.validation.constraints.Digits; 7 | import javax.validation.constraints.Max; 8 | import javax.validation.constraints.NotNull; 9 | 10 | import org.hibernate.validator.constraints.Email; 11 | import org.hibernate.validator.constraints.NotEmpty; 12 | 13 | @Entity 14 | public class DressOrder { 15 | 16 | @Id 17 | @GeneratedValue 18 | private Long id; 19 | 20 | @NotNull 21 | private String name; 22 | 23 | @Email 24 | @NotEmpty 25 | private String email; 26 | 27 | @Digits(fraction = 2, integer = 2) 28 | private Integer size; 29 | 30 | @Max(10) 31 | private String address; 32 | 33 | public DressOrder() { 34 | 35 | } 36 | 37 | public DressOrder(String name, String email, Integer size, String address) { 38 | super(); 39 | this.name = name; 40 | this.email = email; 41 | this.size = size; 42 | this.address = address; 43 | } 44 | 45 | public Long getId() 46 | { 47 | return id; 48 | } 49 | 50 | public void setId(Long id) 51 | { 52 | this.id = id; 53 | } 54 | 55 | public String getName() 56 | { 57 | return name; 58 | } 59 | 60 | public void setName(String name) 61 | { 62 | this.name = name; 63 | } 64 | 65 | public String getEmail() 66 | { 67 | return email; 68 | } 69 | 70 | public void setEmail(String email) 71 | { 72 | this.email = email; 73 | } 74 | 75 | public Integer getSize() 76 | { 77 | return size; 78 | } 79 | 80 | public void setSize(Integer size) 81 | { 82 | this.size = size; 83 | } 84 | 85 | public String getAddress() 86 | { 87 | return address; 88 | } 89 | 90 | public void setAddress(String address) 91 | { 92 | this.address = address; 93 | } 94 | 95 | @Override 96 | public String toString() 97 | { 98 | return "DressOrder [id=" + id + ", name=" + name + ", email=" + email 99 | + ", size=" + size + ", address=" + address + "]
"; 100 | } 101 | 102 | 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/example/etc/validation/DressOrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.etc.validation; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface DressOrderRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/etc/validation/ValidationController.java: -------------------------------------------------------------------------------- 1 | package com.example.etc.validation; 2 | 3 | import javax.validation.Valid; 4 | 5 | import org.springframework.stereotype.Controller; 6 | import org.springframework.ui.Model; 7 | import org.springframework.validation.BindingResult; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | import com.example.App; 12 | 13 | @Controller 14 | public class ValidationController { 15 | 16 | @RequestMapping(value="/validation", method=RequestMethod.POST) 17 | public String validation(Model model,@Valid DressOrder dressOrder, BindingResult result) 18 | { 19 | System.out.println(dressOrder); 20 | if (result.hasErrors()) { 21 | System.out.println("검증에러"); 22 | return App.index; 23 | } 24 | 25 | return App.index; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/collection/MapStudent.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.collection; 2 | 3 | public class MapStudent { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/compoundkey/ComposedIdKey.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.compoundkey; 2 | 3 | import java.io.Serializable; 4 | import java.util.StringTokenizer; 5 | 6 | public class ComposedIdKey implements Serializable { 7 | 8 | private static final long serialVersionUID = 1L; 9 | public String lastname; 10 | public String firstname; 11 | public String city; 12 | 13 | 14 | public ComposedIdKey() { 15 | } 16 | 17 | public ComposedIdKey(String value) { 18 | StringTokenizer token = new StringTokenizer(value, "::"); 19 | this.lastname = token.nextToken(); 20 | this.firstname = token.nextToken(); 21 | this.city = token.nextToken(); 22 | } 23 | 24 | public boolean equals(Object obj) { 25 | if (obj == this) { 26 | return true; 27 | } 28 | if (!(obj instanceof ComposedIdKey)) { 29 | return false; 30 | } 31 | ComposedIdKey c = (ComposedIdKey) obj; 32 | return lastname.equals(c.lastname) && firstname.equals(c.firstname) && city.equals(c.city); 33 | } 34 | 35 | public int hashCode() { 36 | return this.lastname.hashCode() ^ this.firstname.hashCode() ^ this.city.hashCode(); 37 | } 38 | 39 | public String toString() { 40 | return "" + this.lastname + "::" + this.firstname + "::"+this.city; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/compoundkey/CompoundKeyController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.compoundkey; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestMethod; 8 | 9 | import com.example.App; 10 | import com.example.common.BoardArticle; 11 | import com.example.common.BoardArticleRepository; 12 | 13 | @Controller 14 | public class CompoundKeyController { 15 | 16 | @Autowired PeopleManagementRepository repository; 17 | 18 | 19 | @RequestMapping("/compoundkey") 20 | public String compound(Model model){ 21 | 22 | model.addAttribute("data", repository.findAll()); 23 | return App.index; 24 | } 25 | 26 | @RequestMapping(value="/compoundkey", method=RequestMethod.POST) 27 | public String compoundkey(PeopleManagement management, Model model) 28 | { 29 | System.out.println("흠 :"+management); 30 | repository.save(management); 31 | model.addAttribute("data", repository.findAll()); 32 | return App.index; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/compoundkey/PeopleManagement.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.compoundkey; 2 | 3 | import java.io.Serializable; 4 | import java.util.StringTokenizer; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.Id; 9 | import javax.persistence.IdClass; 10 | import javax.persistence.Lob; 11 | import javax.persistence.Table; 12 | 13 | @Entity 14 | @IdClass(ComposedIdKey.class) 15 | public class PeopleManagement { 16 | @Id 17 | @Column(name="lastname") 18 | private String lastname; 19 | @Id 20 | @Column(name="firstname") 21 | private String firstname; 22 | @Id 23 | @Column(name="city") 24 | private String city; 25 | 26 | private String message; 27 | 28 | 29 | public PeopleManagement() { 30 | 31 | } 32 | 33 | 34 | public PeopleManagement(String lastname, String firstname, String city) { 35 | super(); 36 | this.lastname = lastname; 37 | this.firstname = firstname; 38 | this.city = city; 39 | } 40 | 41 | 42 | public PeopleManagement(String lastname, String firstname, String city, 43 | String message) { 44 | super(); 45 | this.lastname = lastname; 46 | this.firstname = firstname; 47 | this.city = city; 48 | this.message = message; 49 | } 50 | 51 | 52 | 53 | 54 | public String getLastname() 55 | { 56 | return lastname; 57 | } 58 | 59 | 60 | public void setLastname(String lastname) 61 | { 62 | this.lastname = lastname; 63 | } 64 | 65 | 66 | public String getFirstname() 67 | { 68 | return firstname; 69 | } 70 | 71 | 72 | public void setFirstname(String firstname) 73 | { 74 | this.firstname = firstname; 75 | } 76 | 77 | 78 | public String getCity() 79 | { 80 | return city; 81 | } 82 | 83 | 84 | public void setCity(String city) 85 | { 86 | this.city = city; 87 | } 88 | 89 | 90 | public String getMessage() 91 | { 92 | return message; 93 | } 94 | 95 | 96 | public void setMessage(String message) 97 | { 98 | this.message = message; 99 | } 100 | 101 | 102 | @Override 103 | public String toString() 104 | { 105 | return "PeopleManagement [lastname=" + lastname + ", firstname=" 106 | + firstname + ", city=" + city + ", message=" + message + "]
"; 107 | } 108 | 109 | 110 | } 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/compoundkey/PeopleManagementRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.compoundkey; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface PeopleManagementRepository extends JpaRepository { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/embedded/EmbeddedController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.embedded; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | import com.example.App; 9 | 10 | @Controller 11 | public class EmbeddedController { 12 | 13 | @Autowired 14 | HumanBodyRepository repository; 15 | 16 | @RequestMapping("/embedded") 17 | public String embedded(Model model) 18 | { 19 | Leg leg = new Leg(); 20 | leg.setKneePowerLeft(100); 21 | leg.setKneePowerRight(200); 22 | 23 | Leg leg2 = new Leg(); 24 | leg2.setKneePowerLeft(1001); 25 | leg2.setKneePowerRight(2002); 26 | 27 | 28 | HumanBody body = new HumanBody(); 29 | body.setLeg1(leg); 30 | body.setLeg2(leg2); 31 | body.setOwnerName("arhanasa"); 32 | repository.save(body); 33 | model.addAttribute("data", repository.findAll()); 34 | 35 | return App.index; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/embedded/HumanBody.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.embedded; 2 | 3 | import javax.persistence.AttributeOverride; 4 | import javax.persistence.AttributeOverrides; 5 | import javax.persistence.Column; 6 | import javax.persistence.Embedded; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | 11 | //I had to make class quickly. naming is not good^^;; excuse me. hehe. 12 | 13 | @Entity 14 | @lombok.Data 15 | public class HumanBody { 16 | 17 | @Id 18 | @GeneratedValue 19 | private Long id; 20 | 21 | @Column(name="ownername") 22 | private String ownerName; 23 | 24 | @Embedded 25 | @AttributeOverrides({ 26 | @AttributeOverride(name="kneePowerLeft", column=@Column(name="kneepowerleft1")), 27 | @AttributeOverride(name="kneePowerRight", column=@Column(name="kneepowerright2")), 28 | }) 29 | private Leg leg1; 30 | 31 | @Embedded 32 | @AttributeOverrides({ 33 | @AttributeOverride(name="kneePowerLeft", column=@Column(name="kneepowerleft3")), 34 | @AttributeOverride(name="kneePowerRight", column=@Column(name="kneepowerright4")), 35 | }) 36 | private Leg leg2; 37 | 38 | 39 | 40 | public HumanBody(Long id, String ownerName, Leg leg1) { 41 | super(); 42 | this.id = id; 43 | this.ownerName = ownerName; 44 | this.leg1 = leg1; 45 | } 46 | 47 | public HumanBody() { 48 | 49 | } 50 | 51 | public Long getId() 52 | { 53 | return id; 54 | } 55 | 56 | public void setId(Long id) 57 | { 58 | this.id = id; 59 | } 60 | 61 | public String getOwnerName() 62 | { 63 | return ownerName; 64 | } 65 | 66 | public void setOwnerName(String ownerName) 67 | { 68 | this.ownerName = ownerName; 69 | } 70 | 71 | 72 | 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/embedded/HumanBodyRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.embedded; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface HumanBodyRepository extends CrudRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/embedded/Leg.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.embedded; 2 | 3 | import lombok.Data; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Embeddable; 7 | 8 | 9 | @Data 10 | @Embeddable 11 | public class Leg { 12 | 13 | private int kneePowerLeft; 14 | private int kneePowerRight; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/join/BaseBallPlayer.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.join; 2 | 3 | import javax.persistence.DiscriminatorColumn; 4 | import javax.persistence.DiscriminatorType; 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | import javax.persistence.Inheritance; 9 | import javax.persistence.InheritanceType; 10 | 11 | @Entity 12 | @Inheritance(strategy=InheritanceType.JOINED) 13 | public abstract class BaseBallPlayer { 14 | 15 | @Id 16 | @GeneratedValue 17 | private Long id; 18 | 19 | private String name; 20 | 21 | public Long getId() 22 | { 23 | return id; 24 | } 25 | 26 | public void setId(Long id) 27 | { 28 | this.id = id; 29 | } 30 | 31 | public String getName() 32 | { 33 | return name; 34 | } 35 | 36 | public void setName(String name) 37 | { 38 | this.name = name; 39 | } 40 | 41 | @Override 42 | public String toString() 43 | { 44 | return "BaseBallPlayer [id=" + id + ", name=" + name + "]"; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/join/BaseBallPlayerRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.join; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface BaseBallPlayerRepository extends CrudRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/join/HanWhaPlayer.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.join; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.PrimaryKeyJoinColumn; 6 | 7 | @Entity 8 | //@PrimaryKeyJoinColumn(name = "student_id", referencedColumnName = "person_id") 9 | public class HanWhaPlayer extends BaseBallPlayer { 10 | 11 | private int eaglesPower; 12 | 13 | 14 | public int getEaglesPower() 15 | { 16 | return eaglesPower; 17 | } 18 | 19 | public void setEaglesPower(int eaglesPower) 20 | { 21 | this.eaglesPower = eaglesPower; 22 | } 23 | 24 | @Override 25 | public String toString() 26 | { 27 | return super.toString() + " and HanWhaPlayer [eaglesPower=" 28 | + eaglesPower + "]
"; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/join/InheritanceJoinController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.join; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | import com.example.App; 9 | 10 | 11 | @Controller 12 | public class InheritanceJoinController { 13 | @Autowired BaseBallPlayerRepository repository; 14 | 15 | @RequestMapping("/inheritanceJoin") 16 | public String inheri(Model model){ 17 | HanWhaPlayer hanWhaPlayer = new HanWhaPlayer(); 18 | hanWhaPlayer.setEaglesPower(400); 19 | hanWhaPlayer.setName("김태균"); 20 | 21 | SkPlayer skPlayer = new SkPlayer(); 22 | skPlayer.setIncheonPower(200); 23 | skPlayer.setName("최정"); 24 | 25 | repository.save(hanWhaPlayer); 26 | repository.save(skPlayer); 27 | model.addAttribute("data", repository.findAll()); 28 | return App.index; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/join/SkPlayer.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.join; 2 | 3 | import javax.persistence.DiscriminatorValue; 4 | import javax.persistence.Entity; 5 | 6 | @Entity 7 | @DiscriminatorValue("sk") 8 | public class SkPlayer extends BaseBallPlayer { 9 | 10 | 11 | 12 | private int incheonPower; 13 | 14 | 15 | public int getIncheonPower() 16 | { 17 | return incheonPower; 18 | } 19 | 20 | public void setIncheonPower(int incheonPower) 21 | { 22 | this.incheonPower = incheonPower; 23 | } 24 | 25 | @Override 26 | public String toString() 27 | { 28 | return super.toString() + " and SkPlayer [incheonPower=" + incheonPower 29 | + "]
"; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/perclass/Module.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.perclass; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | 7 | @Entity 8 | public class Module extends Project{ 9 | 10 | private String moduleName; 11 | 12 | public String getModuleName() { 13 | return moduleName; 14 | } 15 | 16 | public void setModuleName(String moduleName) { 17 | this.moduleName = moduleName; 18 | } 19 | 20 | @Override 21 | public String toString() 22 | { 23 | return super.toString()+" and Module [moduleName=" + moduleName + "]
"; 24 | } 25 | 26 | 27 | 28 | } -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/perclass/PrivateProject.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.perclass; 2 | 3 | import javax.persistence.Entity; 4 | 5 | @Entity 6 | public class PrivateProject extends Project{ 7 | 8 | private String projectManager; 9 | 10 | public String getProjectManager() 11 | { 12 | return projectManager; 13 | } 14 | 15 | public void setProjectManager(String projectManager) 16 | { 17 | this.projectManager = projectManager; 18 | } 19 | 20 | @Override 21 | public String toString() 22 | { 23 | return super.toString()+" and PrivateProject [projectManager=" + projectManager + "]
"; 24 | } 25 | 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/perclass/Project.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.perclass; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.Inheritance; 8 | import javax.persistence.InheritanceType; 9 | 10 | @Entity 11 | @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 12 | public abstract class Project { 13 | 14 | private Long projectId; 15 | private String projectName; 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.TABLE) 19 | public Long getProjectId() { 20 | return projectId; 21 | } 22 | public void setProjectId(Long projectId) { 23 | this.projectId = projectId; 24 | } 25 | public String getProjectName() { 26 | return projectName; 27 | } 28 | public void setProjectName(String projectName) { 29 | this.projectName = projectName; 30 | } 31 | @Override 32 | public String toString() 33 | { 34 | return "Project [projectId=" + projectId + ", projectName=" 35 | + projectName + "]"; 36 | } 37 | 38 | 39 | } -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/perclass/ProjectRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.perclass; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface ProjectRepository extends CrudRepository { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/perclass/inheritancePerClassController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.perclass; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | import com.example.App; 10 | 11 | @Controller 12 | public class inheritancePerClassController { 13 | 14 | 15 | @Autowired ProjectRepository repoPro; 16 | 17 | @RequestMapping("/inheritancePerClass") 18 | public String inheritance(Model model) 19 | { 20 | 21 | Module module = new Module(); 22 | module.setProjectName("inheritance project"); 23 | module.setModuleName("inheritance module"); 24 | 25 | PrivateProject privateProject = new PrivateProject(); 26 | privateProject.setProjectManager("arahansa"); 27 | privateProject.setProjectName("inheritance project"); 28 | 29 | 30 | repoPro.save(module); 31 | repoPro.save(privateProject); 32 | model.addAttribute("data", repoPro.findAll()); 33 | return App.index; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/singletable/Animal.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.singletable; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.Inheritance; 7 | import javax.persistence.InheritanceType; 8 | 9 | @Entity 10 | @Inheritance(strategy = InheritanceType.SINGLE_TABLE) 11 | public abstract class Animal { 12 | 13 | @Id 14 | @GeneratedValue 15 | private Long id; 16 | 17 | private String name; 18 | 19 | 20 | 21 | public Animal() { 22 | } 23 | public Animal(String name) { 24 | super(); 25 | this.name = name; 26 | } 27 | 28 | public Long getId() 29 | { 30 | return id; 31 | } 32 | 33 | public void setId(Long id) 34 | { 35 | this.id = id; 36 | } 37 | 38 | public String getName() 39 | { 40 | return name; 41 | } 42 | 43 | public void setName(String name) 44 | { 45 | this.name = name; 46 | } 47 | @Override 48 | public String toString() 49 | { 50 | return "Animal [id=" + id + ", name=" + name + "]"; 51 | } 52 | 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/singletable/AnimalRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.singletable; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface AnimalRepository extends CrudRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/singletable/Bird.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.singletable; 2 | 3 | import javax.persistence.Entity; 4 | 5 | @Entity 6 | public class Bird extends Animal{ 7 | 8 | private String nameNest; 9 | 10 | public String getNameNest() 11 | { 12 | return nameNest; 13 | } 14 | 15 | public void setNameNest(String nameNest) 16 | { 17 | this.nameNest = nameNest; 18 | } 19 | 20 | @Override 21 | public String toString() 22 | { 23 | return super.toString()+"and Bird [nameNest=" + nameNest + "]+
"; 24 | } 25 | 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/singletable/InheritanceSingleController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.singletable; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | import com.example.App; 9 | 10 | @Controller 11 | public class InheritanceSingleController { 12 | 13 | @Autowired AnimalRepository repoAnimal; 14 | 15 | @RequestMapping("/inheritanceSingle") 16 | public String animal(Model model){ 17 | Bird bird = new Bird(); 18 | bird.setName("파랑새"); 19 | bird.setNameNest("희망봉"); 20 | repoAnimal.save(bird); 21 | 22 | Lion lion = new Lion(); 23 | lion.setName("심바"); 24 | lion.setNameFood("품바"); 25 | repoAnimal.save(lion); 26 | model.addAttribute("data", repoAnimal.findAll() 27 | +"
" 28 | +"
" 29 | +"
" 30 | ); 31 | return App.index; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/inheritance/singletable/Lion.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.inheritance.singletable; 2 | 3 | import javax.persistence.Entity; 4 | 5 | @Entity 6 | public class Lion extends Animal{ 7 | private String nameFood; 8 | 9 | public Lion() { 10 | 11 | } 12 | public Lion(String nameFood) { 13 | super(); 14 | this.nameFood = nameFood; 15 | } 16 | 17 | public String getNameFood() 18 | { 19 | return nameFood; 20 | } 21 | 22 | public void setNameFood(String nameFood) 23 | { 24 | this.nameFood = nameFood; 25 | } 26 | @Override 27 | public String toString() 28 | { 29 | return super.toString()+"and Lion [nameFood=" + nameFood + "]
"; 30 | } 31 | 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/mappedsuperclass/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.mappedsuperclass; 2 | 3 | import org.hibernate.annotations.Type; 4 | import org.joda.time.DateTime; 5 | 6 | import javax.persistence.*; 7 | 8 | 9 | /** 10 | * @author Petri 11 | * 이 분 블로그 주소 : http://www.petrikainulainen.net/ 12 | */ 13 | 14 | @MappedSuperclass 15 | public abstract class BaseEntity { 16 | 17 | @Column(name = "creation_time", nullable = false) 18 | @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") 19 | private DateTime creationTime; 20 | 21 | @Column(name = "modification_time", nullable = false) 22 | @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") 23 | private DateTime modificationTime; 24 | 25 | @Version 26 | private long version; 27 | 28 | public abstract ID getId(); 29 | 30 | public DateTime getCreationTime() { 31 | return creationTime; 32 | } 33 | 34 | public DateTime getModificationTime() { 35 | return modificationTime; 36 | } 37 | 38 | public long getVersion() { 39 | return version; 40 | } 41 | 42 | @PrePersist 43 | public void prePersist() { 44 | DateTime now = DateTime.now(); 45 | this.creationTime = now; 46 | this.modificationTime = now; 47 | } 48 | 49 | @PreUpdate 50 | public void preUpdate() { 51 | this.modificationTime = DateTime.now(); 52 | } 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/mappedsuperclass/MappedController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.mappedsuperclass; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | import com.example.App; 10 | 11 | @Controller 12 | public class MappedController { 13 | 14 | @Autowired MappedSuperRepository repository; 15 | 16 | @RequestMapping("/mappedSuperclass") 17 | 18 | public String mapped(Model model){ 19 | MappedSupper mappedSupper = new MappedSupper(); 20 | mappedSupper.setName("arahanas"); 21 | repository.save(mappedSupper); 22 | model.addAttribute("data", repository.findAll()+"

" 23 | +"
" 24 | +"

"); 25 | return App.index; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/mappedsuperclass/MappedSuperRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.mappedsuperclass; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface MappedSuperRepository extends CrudRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/mappedsuperclass/MappedSupper.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.mappedsuperclass; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | 7 | @Entity 8 | public class MappedSupper extends BaseEntity { 9 | 10 | @Id 11 | @GeneratedValue 12 | private Long id; 13 | 14 | private String name; 15 | 16 | @Override 17 | public Long getId() 18 | { 19 | return id; 20 | } 21 | 22 | public String getName() 23 | { 24 | return name; 25 | } 26 | 27 | public void setName(String name) 28 | { 29 | this.name = name; 30 | } 31 | 32 | public void setId(Long id) 33 | { 34 | this.id = id; 35 | } 36 | 37 | @Override 38 | public String toString() 39 | { 40 | return super.toString()+ "and MappedSupper [id=" + id + ", name=" + name + "]
"; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/secondary/SecondaryController.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.secondary; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | import com.example.App; 9 | 10 | @Controller 11 | public class SecondaryController { 12 | 13 | @Autowired 14 | SecondaryRepository repository; 15 | 16 | @RequestMapping("/secondary") 17 | public String secondary(Model model) 18 | { 19 | Secondarymaster master = new Secondarymaster(); 20 | master.setSub1("hello"); 21 | master.setSub2("world"); 22 | repository.save(master); 23 | model.addAttribute("data", "테이블이 두개로 되어있다
"+repository.findAll()+ 24 | "

"+ 25 | "

"+ 26 | "
" 27 | ); 28 | return App.index; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/secondary/SecondaryRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.secondary; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface SecondaryRepository extends JpaRepository{ 6 | Secondarymaster findBySub2(String sub2); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/mapping/secondary/Secondarymaster.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.secondary; 2 | 3 | import javax.persistence.Basic; 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.persistence.PrimaryKeyJoinColumn; 10 | import javax.persistence.SecondaryTable; 11 | 12 | @Entity 13 | @SecondaryTable(name="sub1secondary", pkJoinColumns=@PrimaryKeyJoinColumn( 14 | name="SECONDARYMASTER_ID_FPK", referencedColumnName="SECONDARYMASTER_ID_PK" 15 | ) 16 | ) 17 | public class Secondarymaster { 18 | 19 | @Id 20 | @GeneratedValue 21 | @Column(name="SECONDARYMASTER_ID_PK") 22 | private Long id; 23 | 24 | @Basic(fetch=FetchType.LAZY) 25 | //lazy로 불러오는 게 안되나? 쿼리보니깐..음..다 불러오는 것같은데..? 26 | @Column(table="sub1secondary", name="sub1") 27 | private String sub1; 28 | 29 | @Column(name="sub2") 30 | private String sub2; 31 | 32 | public Secondarymaster() { 33 | 34 | } 35 | 36 | 37 | 38 | 39 | public Secondarymaster(String sub1, String sub2) { 40 | super(); 41 | this.sub1 = sub1; 42 | this.sub2 = sub2; 43 | } 44 | 45 | 46 | public Long getId() 47 | { 48 | return id; 49 | } 50 | 51 | public void setId(Long id) 52 | { 53 | this.id = id; 54 | } 55 | 56 | public String getSub1() 57 | { 58 | return sub1; 59 | } 60 | 61 | public void setSub1(String sub1) 62 | { 63 | this.sub1 = sub1; 64 | } 65 | 66 | public String getSub2() 67 | { 68 | return sub2; 69 | } 70 | 71 | public void setSub2(String sub2) 72 | { 73 | this.sub2 = sub2; 74 | } 75 | 76 | @Override 77 | public String toString() 78 | { 79 | return "Secondarymaster [id=" + id + ", sub1=" + sub1 + ", sub2=" 80 | + sub2 + "]
"; 81 | } 82 | 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/example/query/jpql/JPQLController.java: -------------------------------------------------------------------------------- 1 | package com.example.query.jpql; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.EntityManager; 6 | 7 | import org.apache.catalina.util.SessionConfig; 8 | import org.hibernate.Query; 9 | import org.hibernate.Session; 10 | import org.hibernate.SessionFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.stereotype.Controller; 13 | import org.springframework.ui.Model; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | 16 | import com.example.App; 17 | import com.example.common.BoardArticle; 18 | import com.example.common.BoardArticleRepository; 19 | 20 | @Controller 21 | public class JPQLController { 22 | 23 | private static final String JPQL = "from BoardArticle"; 24 | 25 | @Autowired 26 | EntityManager em; 27 | 28 | @Autowired 29 | SessionFactory sessionFactory; 30 | 31 | @Autowired BoardArticleRepository repository; 32 | 33 | @RequestMapping("/jpql") 34 | public String jpql(Model model){ 35 | BoardArticle article = new BoardArticle("arahansa", "hello world", "content"); 36 | repository.save(article); 37 | 38 | Session session = sessionFactory.openSession(); 39 | session.beginTransaction(); 40 | Query query = session.createQuery(JPQL); 41 | List listArticles = query.list(); 42 | 43 | session.getTransaction().commit(); 44 | session.close(); 45 | 46 | model.addAttribute("data", listArticles); 47 | 48 | return App.index; 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/justone/JustOne.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.justone; 2 | 3 | import java.util.Date; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.Enumerated; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | import javax.persistence.Temporal; 12 | import javax.persistence.TemporalType; 13 | import javax.persistence.Transient; 14 | 15 | @Entity 16 | @Table(name="justone") 17 | public class JustOne { 18 | 19 | @Id // 주키생성 20 | @GeneratedValue //자동생성. 자세한 것은 API 혹은 서적 참고 21 | private Long id; 22 | 23 | @Column(name="msg" , length=100) //테이블에 저장될 때 컬럼네임 msg, 길이 100 24 | private String message; 25 | 26 | @Temporal(TemporalType.DATE) //날짜 저장형식. type 에 date, time, timestamp 27 | private Date dateJoin; 28 | 29 | @Enumerated // enum 저장 형식. 자세한 것은 API 혹은 서적 참고 30 | private JustOneEnum enumOne; 31 | 32 | 33 | @Transient // transient 는 저장하지 않습니다. 34 | private String passwordConfirm; 35 | 36 | 37 | public Long getId() { 38 | return id; 39 | } 40 | 41 | public void setId(Long id) { 42 | this.id = id; 43 | } 44 | 45 | public String getMessage() { 46 | return message; 47 | } 48 | 49 | public void setMessage(String message) { 50 | this.message = message; 51 | } 52 | 53 | public Date getDateJoin() { 54 | return dateJoin; 55 | } 56 | 57 | public void setDateJoin(Date dateJoin) { 58 | this.dateJoin = dateJoin; 59 | } 60 | 61 | public JustOneEnum getEnumOne() { 62 | return enumOne; 63 | } 64 | 65 | public void setEnumOne(JustOneEnum enumOne) { 66 | this.enumOne = enumOne; 67 | } 68 | 69 | public String getPasswordConfirm() { 70 | return passwordConfirm; 71 | } 72 | 73 | public void setPasswordConfirm(String passwordConfirm) { 74 | this.passwordConfirm = passwordConfirm; 75 | } 76 | 77 | @Override 78 | public String toString() 79 | { 80 | return "JustOne [id=" + id + ", message=" + message + ", dateJoin(TemporalType)=" 81 | + dateJoin + ", enumOne=" + enumOne + ", passwordConfirm(transient)=" 82 | + passwordConfirm + "]
"; 83 | } 84 | 85 | 86 | 87 | 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/justone/JustOneController.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.justone; 2 | 3 | import java.util.Date; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.ui.Model; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | 10 | import com.example.App; 11 | 12 | @Controller 13 | public class JustOneController { 14 | 15 | @Autowired JustOneRepository repository; 16 | 17 | @RequestMapping("one") 18 | public String test(Model model){ 19 | JustOne one = new JustOne(); 20 | one.setDateJoin(new Date()); 21 | one.setEnumOne(JustOneEnum.ONE); 22 | one.setMessage("hello"); 23 | one.setPasswordConfirm("1234"); 24 | repository.save(one); 25 | 26 | model.addAttribute("data", repository.findAll()+"

"); 27 | 28 | return App.index; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/justone/JustOneEnum.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.justone; 2 | 3 | public enum JustOneEnum { 4 | ONE, TWO 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/justone/JustOneRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.justone; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | 9 | public interface JustOneRepository extends JpaRepository{ 10 | public JustOne findByMessage(String message); 11 | public List findBydateJoinBeforeAndMessage(Date date, String message); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/manytomany/Book.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.manytomany; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.JoinTable; 11 | import javax.persistence.ManyToMany; 12 | 13 | @Entity 14 | public class Book{ 15 | @ManyToMany 16 | @JoinTable(name = "BOOK_CATEGORY", 17 | joinColumns=@JoinColumn(name = "BOOK_ID_FRK"), 18 | inverseJoinColumns = @JoinColumn(name = "CATEGORY_ID_FPK")) 19 | private Set categories = new HashSet(); 20 | 21 | @Id 22 | @GeneratedValue 23 | private Long id; 24 | private String name; 25 | private int price; 26 | 27 | 28 | 29 | 30 | 31 | public Book() { 32 | } 33 | 34 | public Book(String name) { 35 | super(); 36 | this.name = name; 37 | } 38 | 39 | 40 | 41 | public Long getId() { 42 | return id; 43 | } 44 | 45 | public void setId(Long id) { 46 | this.id = id; 47 | } 48 | 49 | public String getName() { 50 | return name; 51 | } 52 | 53 | public void setName(String name) { 54 | this.name = name; 55 | } 56 | 57 | public int getPrice() { 58 | return price; 59 | } 60 | 61 | public void setPrice(int price) { 62 | this.price = price; 63 | } 64 | 65 | public Set getCategories() { 66 | return categories; 67 | } 68 | 69 | public void setCategories(Set categories) { 70 | this.categories = categories; 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "
Book [id=" + id + ", name=" + name + ", price=" + price + "]"; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/manytomany/BookRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.manytomany; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface BookRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/manytomany/Category.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.manytomany; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.JoinTable; 11 | import javax.persistence.ManyToMany; 12 | 13 | @Entity 14 | public class Category{ 15 | @ManyToMany 16 | @JoinTable(name = "BOOK_CATEGORY", 17 | joinColumns= @JoinColumn(name = "CATEGORY_ID_FPK"), 18 | inverseJoinColumns=@JoinColumn(name = "BOOK_ID_FRK")) 19 | private Set books = new HashSet(); 20 | 21 | 22 | @Id @GeneratedValue 23 | private Long id; 24 | private String name; 25 | 26 | 27 | 28 | public Category() { 29 | } 30 | 31 | public Category(String name) { 32 | super(); 33 | this.name = name; 34 | } 35 | 36 | 37 | public Long getId() { 38 | return id; 39 | } 40 | 41 | public void setId(Long id) { 42 | this.id = id; 43 | } 44 | 45 | public String getName() { 46 | return name; 47 | } 48 | 49 | public void setName(String name) { 50 | this.name = name; 51 | } 52 | 53 | public Set getBooks() { 54 | return books; 55 | } 56 | 57 | public void setBooks(Set books) { 58 | this.books = books; 59 | } 60 | 61 | @Override 62 | public String toString() { 63 | return "Category [id=" + id + ", name=" + name + "]"+"
"+ 64 | "(ManyTomany)"+getBooks(); 65 | } 66 | 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/manytomany/CategoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.manytomany; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface CategoryRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/manytomany/ManyToManyController.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.manytomany; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | 8 | import com.example.App; 9 | 10 | @Controller 11 | public class ManyToManyController { 12 | 13 | @Autowired BookRepository repoBook; 14 | @Autowired CategoryRepository repoCate; 15 | 16 | @RequestMapping("/manytomany") 17 | public String manytoMany(Model model){ 18 | Book book = new Book("MB's Cost"); 19 | Book book1 = new Book("Queen. Park"); 20 | Book book2 = new Book("Revenge of Yoo"); 21 | Book book3 = new Book("Hitman"); 22 | 23 | Category category = new Category(); 24 | category.setName("Politics"); 25 | category.getBooks().add(book); 26 | category.getBooks().add(book1); 27 | category.getBooks().add(book2); 28 | category.getBooks().add(book3); 29 | 30 | repoBook.save(book); 31 | repoBook.save(book1); 32 | repoBook.save(book2); 33 | repoBook.save(book3); 34 | repoCate.save(category); 35 | model.addAttribute("data", repoCate.getOne(1L)+"
" 36 | +"
" 37 | +"
" 38 | ); 39 | return App.index; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetomany/OnetoManyController.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetomany; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.ui.Model; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | import com.example.App; 14 | 15 | @Controller 16 | public class OnetoManyController { 17 | @Autowired UniversityRepository repository; 18 | @RequestMapping("/onetomany") 19 | public String onetomanyinit(Model model) { 20 | //객체선언 21 | University university = new University(); 22 | university.setId(1L); 23 | university.setName("arahansa"); 24 | //students 설정후 저장 25 | List students = new ArrayList(); 26 | for (int i = 0; i < 15; i++){ 27 | students.add(new Student("arahan"+i, "010-"+i, university)); 28 | } 29 | university.setStudents(students); 30 | repository.save(university); 31 | //완료 32 | model.addAttribute("data", repository.getOne(1L).toStringPlusStudents() 33 | +"

" 34 | +"

" 35 | +"

" 36 | ); 37 | return App.index; 38 | } 39 | 40 | @RequestMapping("/university") 41 | @ResponseBody 42 | public String university() { 43 | University getUniversity = repository.getOne(1L); 44 | return getUniversity.toString(); 45 | } 46 | 47 | @RequestMapping("/univandstudents") 48 | @ResponseBody 49 | public String univandstudents() { 50 | University getUniversity = repository.getOne(1L); 51 | return getUniversity.toStringPlusStudents(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetomany/Student.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetomany; 2 | 3 | 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.ManyToOne; 9 | 10 | @Entity 11 | public class Student{ 12 | @ManyToOne 13 | @JoinColumn(name="university_id") 14 | private University university; 15 | 16 | @Id @GeneratedValue 17 | private Long id; 18 | private String name; 19 | private String numPhone; 20 | 21 | 22 | public Student() { 23 | } 24 | public Student(String name, String numPhone, University university) { 25 | super(); 26 | this.name = name; 27 | this.numPhone = numPhone; 28 | this.university = university; 29 | } 30 | 31 | 32 | public Long getId() { 33 | return id; 34 | } 35 | public void setId(Long id) { 36 | this.id = id; 37 | } 38 | public String getName() { 39 | return name; 40 | } 41 | public void setName(String name) { 42 | this.name = name; 43 | } 44 | public String getNumPhone() { 45 | return numPhone; 46 | } 47 | public void setNumPhone(String numPhone) { 48 | this.numPhone = numPhone; 49 | } 50 | public University getUniversity() { 51 | return university; 52 | } 53 | public void setUniversity(University university) { 54 | this.university = university; 55 | } 56 | @Override 57 | public String toString() { 58 | return "Student [id=" + id + ", name=" + name + ", numPhone=" + numPhone + "]"; 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetomany/University.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetomany; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Entity; 7 | import javax.persistence.FetchType; 8 | import javax.persistence.Id; 9 | import javax.persistence.OneToMany; 10 | 11 | @Entity 12 | public class University{ 13 | @OneToMany( 14 | targetEntity=Student.class, 15 | mappedBy="university", 16 | cascade=CascadeType.ALL, 17 | fetch=FetchType.LAZY) 18 | private List students; 19 | 20 | 21 | @Id 22 | private Long id; 23 | private String name; 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | public Long getId() { 32 | return id; 33 | } 34 | public void setId(Long id) { 35 | this.id = id; 36 | } 37 | public String getName() { 38 | return name; 39 | } 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | public List getStudents() { 44 | return students; 45 | } 46 | public void setStudents(List students) { 47 | this.students = students; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "University [id=" + id + ", name=" + name + "]"; 53 | } 54 | 55 | public String toStringPlusStudents(){ 56 | StringBuilder builder = new StringBuilder(); 57 | builder.append("University [id=" + id + ", name=" + name + "]
"); 58 | builder.append("Students
"); 59 | builder.append("====================
"); 60 | for (Student student : students) 61 | builder.append(student.toString()+"
"); 62 | builder.append("================
"); 63 | builder.append("Complete"); 64 | return builder.toString(); 65 | } 66 | 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetomany/UniversityRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetomany; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface UniversityRepository extends JpaRepository{} 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetoone/Member.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetoone; 2 | 3 | import javax.persistence.CascadeType; 4 | import javax.persistence.Entity; 5 | import javax.persistence.FetchType; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.Id; 8 | import javax.persistence.JoinColumn; 9 | import javax.persistence.OneToOne; 10 | 11 | @Entity 12 | public class Member { 13 | 14 | @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 15 | @JoinColumn(name = "mDetail_FK") 16 | private MemberDetail memberDetail; 17 | 18 | 19 | 20 | @Id 21 | @GeneratedValue 22 | private Long id; 23 | private String name; 24 | 25 | 26 | 27 | public MemberDetail getMemberDetail() { 28 | return memberDetail; 29 | } 30 | 31 | public void setMemberDetail(MemberDetail memberDetail) { 32 | this.memberDetail = memberDetail; 33 | } 34 | 35 | public Long getId() { 36 | return id; 37 | } 38 | 39 | public void setId(Long id) { 40 | this.id = id; 41 | } 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "Member [id=" + id + ", name=" + name + "]
+(OneToOne) "+memberDetail; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetoone/MemberDetail.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetoone; 2 | 3 | import java.util.Arrays; 4 | 5 | import javax.persistence.Basic; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.Id; 9 | import javax.persistence.Lob; 10 | import javax.persistence.OneToOne; 11 | 12 | @Entity 13 | public class MemberDetail { 14 | @OneToOne(mappedBy="memberDetail") 15 | private Member member; 16 | 17 | 18 | @Id @GeneratedValue 19 | private Long id; 20 | 21 | 22 | private String address; 23 | 24 | @Lob @Basic 25 | private byte[] picture; 26 | 27 | public Long getId() { 28 | return id; 29 | } 30 | 31 | public void setId(Long id) { 32 | this.id = id; 33 | } 34 | 35 | public Member getMember() { 36 | return member; 37 | } 38 | 39 | public void setMember(Member member) { 40 | this.member = member; 41 | } 42 | 43 | public String getAddress() { 44 | return address; 45 | } 46 | 47 | public void setAddress(String address) { 48 | this.address = address; 49 | } 50 | 51 | public byte[] getPicture() { 52 | return picture; 53 | } 54 | 55 | public void setPicture(byte[] picture) { 56 | this.picture = picture; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "MemberDetail [id=" + id + ", picture=" + Arrays.toString(picture) + "]"; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetoone/MemberRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetoone; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface MemberRepository extends JpaRepository{ 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/r_mapping/onetoone/OnetoOneController.java: -------------------------------------------------------------------------------- 1 | package com.example.r_mapping.onetoone; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | 9 | import com.example.App; 10 | 11 | @Controller 12 | public class OnetoOneController { 13 | @Autowired MemberRepository repository; 14 | 15 | @RequestMapping("onetoone") 16 | public String member(Model model){ 17 | Member member = new Member(); 18 | member.setName("arahansa"); 19 | MemberDetail memberDetail = new MemberDetail(); 20 | memberDetail.setAddress("incheon"); 21 | member.setMemberDetail(memberDetail); 22 | repository.save(member); 23 | model.addAttribute("data", member.toString() 24 | +"
" 25 | +"
" 26 | +"
" 27 | ); 28 | return App.index; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server.port: 9000 2 | spring.profiles.active: local 3 | 4 | spring: 5 | view: 6 | prefix: /WEB-INF/views/ 7 | suffix: .jsp -------------------------------------------------------------------------------- /src/main/resources/db-config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | spring.profiles: test2 3 | 4 | spring.datasource: 5 | url: jdbc:mysql://localhost:3306/learnspringdatajpa 6 | driverClassName: com.mysql.jdbc.Driver 7 | username: arahansa 8 | password: 1234 9 | spring.jpa: 10 | database-platform: org.hibernate.dialect.MySQL5InnoDBDialect 11 | show-sql: true 12 | ddl-auto: create-drop 13 | 14 | --- 15 | spring.profiles: test 16 | 17 | spring.datasource: 18 | url: jdbc:h2:tcp://localhost/~/learnspringdatajpa;DB_CLOSE_ON_EXIT=FALSE 19 | driverClassName: org.h2.Driver 20 | username: sa 21 | password: 22 | spring.jpa.database-platform: org.hibernate.dialect.H2Dialect 23 | 24 | --- 25 | spring.profiles: local 26 | 27 | spring.datasource: 28 | url: jdbc:h2:~/learningspringdatajpa;DB_CLOSE_ON_EXIT=FALSE 29 | driverClassName: org.h2.Driver 30 | username: sa 31 | password: 32 | spring.jpa.database-platform: org.hibernate.dialect.H2Dialect 33 | spring.jpa.show-sql: true 34 | spring.jpa.hibernate.ddl-auto: create-drop 35 | -------------------------------------------------------------------------------- /src/main/resources/locale/messages_kr_KR.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | messages.properties 5 | 주소의 최대 길이는 {1} 자입니다. 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/main/resources/rebel.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/main/resources/static/images/inheritancesingle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/inheritancesingle.png -------------------------------------------------------------------------------- /src/main/resources/static/images/inheritancesingle2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/inheritancesingle2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/inheritancesingle3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/inheritancesingle3.png -------------------------------------------------------------------------------- /src/main/resources/static/images/justone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/justone.png -------------------------------------------------------------------------------- /src/main/resources/static/images/manytomany.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/manytomany.png -------------------------------------------------------------------------------- /src/main/resources/static/images/manytomany2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/manytomany2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/manytomany3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/manytomany3.png -------------------------------------------------------------------------------- /src/main/resources/static/images/mappedsupper.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/mappedsupper.png -------------------------------------------------------------------------------- /src/main/resources/static/images/mappedsupper2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/mappedsupper2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/mappedsupper3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/mappedsupper3.png -------------------------------------------------------------------------------- /src/main/resources/static/images/me.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/me.jpg -------------------------------------------------------------------------------- /src/main/resources/static/images/onetomany.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetomany.png -------------------------------------------------------------------------------- /src/main/resources/static/images/onetomany2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetomany2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/onetomany3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetomany3.png -------------------------------------------------------------------------------- /src/main/resources/static/images/onetoone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetoone.png -------------------------------------------------------------------------------- /src/main/resources/static/images/onetoone2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetoone2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/onetoone3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/onetoone3.png -------------------------------------------------------------------------------- /src/main/resources/static/images/secondary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/secondary.png -------------------------------------------------------------------------------- /src/main/resources/static/images/secondary2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/secondary2.png -------------------------------------------------------------------------------- /src/main/resources/static/images/secondary3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arahansa/learnspringdatajpa/262c9d658ad8d2f59947691edb5df8b304a9b4ae/src/main/resources/static/images/secondary3.png -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/views/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=UTF-8" 2 | pageEncoding="UTF-8"%> 3 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 4 | <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 | 6 | 7 | 8 | 9 | 아라한사의 jpa정리 10 | 17 | 18 | 19 | 20 | 21 |
22 |

받은 데이터

23 | ${data } 24 |
25 |
26 |
27 |
28 |
29 |

관계매핑

30 |
    31 |
  • 32 | 단일 매핑해본 것 /one = 영속성 컨텍스트로 인해 마지막 JustOne은 값을 캐싱하고 있다. 33 |
    고로 이것을 누를 수록 마지막에의 저스트원 값만 다른 것을 볼 수가 있을 것이다.
    34 | 패키지 이름 : com.example.r_mapping.justone 35 |
  • 36 |
  • 37 | 일대일매핑 /onetoone = 멤버와 멤버 세부사항이 일대일로 묶여있다. 38 | 패키지 이름 : com.example.r_mapping.onetoone 39 |
  • 40 |
  • 41 | 일대다매핑 /onetomany = 대학 하나에 묶인 학생들을 가져온다. 42 | 패키지 이름 : com.example.r_mapping.onetomany 43 |
  • 44 |
  • 45 | 다대다매핑 /manytomany = 다대다매핑이다. 카테고리 하나에 대해서 책을 가져옵니다. 46 | 패키지 이름 : com.example.r_mapping.manytomany 47 |
  • 48 | 49 |
50 |

Spring Data Jpa, Query DSL 를 이용한 검색

51 |
52 | 잠시 설명 : 53 | 게시글(BoardArticle), 사용자(User), 댓글(Comment), 태그(Tags) 를 가지고 있다고 가정해보자.
54 | 게시글과 사용자는 일대일 매핑을 하고 있으며 , 게시글과 댓글은 일대다, 태그와 게시글은 다대다 관계를 가진다.
55 | 사용자와 댓글또한 일대일 관계를 가진다. 여기에 무작위로 데이터를 넣어보고 조건에 따라 가져와보겠다!! 56 |
57 |
    58 |
  • 59 | spring data jpa 기본 : 60 |
    61 | 사용자 정보: 62 | 63 |
    64 | 65 | 66 | 67 |
    68 | 레퍼런스 : http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation 69 | 슬립(하단에도 검색 나옴^^) : http://slipp.net/wiki/pages/viewpage.action?pageId=24641728 70 |
  • 71 |
  • springdatajpa- specification
  • 72 |
  • query dsl
  • 73 | 74 |
75 | 76 |

다른 매핑

77 |
    78 |
  • 79 | 세컨더리테이블 /secondary = 필드를 바깥 테이블로 빼낼 수 있다. 80 | 패키지 이름 : com.example.mapping.secondary 81 |
  • 82 |
  • 83 | @MappedSuperclass /mappedSuperclass = 상속을 하면서 부모클래스의 필드를 모두 가져온다. 84 | 패키지 이름 : com.example.mapping.mappedsuperclass 85 | @PrePersist, @PreUpdate 어노테이션을 BasicEntity에 포함.(petri님 소스 참고) 86 |
  • 87 |
  • 88 | 상속매핑(단일테이블) : /inheritanceSingle = 각각의 상속을 단일테이블로 묶는다 89 | 패키지 이름 : com.example.mapping.inheritance.singletable 90 |
  • 91 |
  • 92 | 상속매핑(클래스당테이블) : /inheritancePerClass = 상속한 클래스마다 테이블을 만든다. 93 | 패키지 이름 : com.example.mapping.inheritance.perclass 94 |
  • 95 |
  • 96 | 상속매핑(조인) : /inheritanceJoin = 공통부분을 분리시키고 조인으로 가져온다. 97 | 패키지 이름 : com.example.mapping.inheritance.join 98 | 참고할만한 링크 : http://www.javaroots.com/2013/07/hibernate-inheritance-joined-strategy.html 99 |
  • 100 | 101 |
  • 102 | 컴파운드키 : /compoundkey = 변수를 조합해서 하나의 키로 써본다. 103 | 패키지 이름 : com.example.mapping.compoundkey 104 | 여기서 이름, 성, 사는 도시 세개 합친 세트([이름,성,도시]) 중에 하나라도 겹치면 데이터가 안 들어간다. 105 | 비슷한 기능으로 @UniqueConstrains 어노테이션도 있다 106 |
    107 | 108 | 109 | 110 | 111 | 112 |
    113 |
  • 114 | 115 |
  • 116 | Embedded : /embedded = 다른 엔티티에 내장시킬 수 있다. 117 | 패키지 이름 : com.example.mapping.embedded 118 | @AttributeOverrides 도 같이 나온다. 속성을 오버라이딩해서 재정의 하는 것이다. 119 |
  • 120 |
121 | 122 |

콜렉션 매핑

123 |
    124 |
  • 125 |
126 | 127 | 128 |

다른 검색

129 |
    130 |
  • JPQL : /jpql = jpql을 이용한 검색
  • 131 |
  • Criteria :
  • 132 |
  • NamedQuery :
  • 133 |
134 | 135 |

검증

136 |
    137 |
  • 138 | <%-- 139 | 140 | 141 | 142 | 143 | 144 | 145 | --%> 146 |
  • 147 |
148 | 149 |
150 | 주의사항과 기타 : 151 | 코드와 매뉴얼로 이야기합니다 by 아라한사 152 | 153 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/test/java/com/example/mapping/justone/JustOneRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.justone; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | import java.util.GregorianCalendar; 9 | import java.util.List; 10 | 11 | import javax.transaction.Transactional; 12 | 13 | import org.junit.Before; 14 | import org.junit.Test; 15 | import org.junit.runner.RunWith; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.boot.test.SpringApplicationConfiguration; 18 | import org.springframework.data.domain.Page; 19 | import org.springframework.data.domain.PageRequest; 20 | import org.springframework.data.domain.Pageable; 21 | import org.springframework.data.domain.Sort; 22 | import org.springframework.data.domain.Sort.Direction; 23 | import org.springframework.test.context.ActiveProfiles; 24 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 25 | 26 | import com.example.App; 27 | import com.example.r_mapping.justone.JustOne; 28 | import com.example.r_mapping.justone.JustOneEnum; 29 | import com.example.r_mapping.justone.JustOneRepository; 30 | 31 | 32 | @RunWith(SpringJUnit4ClassRunner.class) 33 | @SpringApplicationConfiguration(classes=App.class) 34 | @Transactional 35 | @ActiveProfiles("test") 36 | public class JustOneRepositoryTest { 37 | 38 | private static final int numRequest = 10; 39 | private static final String _1234 = "1234"; 40 | private static final String HELLO_WORLD = "hello world"; 41 | 42 | @Autowired JustOneRepository repository; 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | //Justone객체를 하나 만들고 save 로 저장합니다. 47 | //asserteq 에서 총 개수가 1이란 것을 확인해봅니다. 48 | JustOne one = new JustOne(); 49 | one.setDateJoin(new Date()); 50 | one.setEnumOne(JustOneEnum.TWO); 51 | one.setMessage(HELLO_WORLD); 52 | one.setPasswordConfirm(_1234); 53 | repository.save(one); 54 | assertEquals(repository.count(), 1); 55 | } 56 | 57 | @Test 58 | public void 읽고난뒤수정() throws Exception { 59 | //먼저 맨끝의 하나를 읽어보겠습니다. 읽어온 것의 메시지가 헬로월드가 맞는지 확인해보고 60 | List ones = repository.findAll(); 61 | JustOne one = ones.get(ones.size()-1); 62 | assertEquals(one.getMessage(), HELLO_WORLD); 63 | //메시지를 수정한 뒤에 저장후, 다시 받아와서 문자열이 변했는지를 확인해봅니다. 64 | one.setMessage("ni3hao3"); 65 | repository.save(one); 66 | JustOne getOne = repository.getOne(one.getId()); 67 | assertEquals(getOne.getMessage(), one.getMessage()); 68 | } 69 | 70 | 71 | @Test 72 | public void 삭제() throws Exception { 73 | //repository.deleteAll 로 모두 지우고서 count를 0 확인해봅니다. 74 | repository.deleteAll(); 75 | assertEquals(repository.count(), 0); 76 | } 77 | 78 | 79 | @Test 80 | public void 페이징테스트() throws Exception { 81 | repository.deleteAll(); 82 | //자 일단 40개 정도 저장을 해봅시다. 83 | for (int i = 0; i < 40; i++) { 84 | JustOne one = new JustOne(); 85 | one.setDateJoin(new Date()); 86 | one.setEnumOne(JustOneEnum.TWO); 87 | one.setMessage(HELLO_WORLD+i); 88 | one.setPasswordConfirm(_1234); 89 | repository.save(one); 90 | } 91 | //PageRequest 에 시작페이지와 요청갯수를 넣어주고 repository에 넣어줍니다. 92 | Pageable pageable = new PageRequest(0, numRequest); 93 | Page ones = repository.findAll(pageable); 94 | 95 | // 페이지 객체에서 받은 것에서 getContent 하시면 리스트가 뿅 나옵니다~_~ 96 | //메시지를 잘 뽑아오는 지 테스트해보고~ 97 | List onesList = ones.getContent(); 98 | for (int i = 0; i < numRequest; i++) { 99 | assertEquals(onesList.get(i).getMessage(), HELLO_WORLD+i); 100 | } 101 | assertEquals(onesList.size(), numRequest); 102 | 103 | //역순으로 하고 싶으시다면?! 소트를 써봅시다. 104 | // 0개부터 39개까지 헬로월드 메시지를 넣었는데, id 역순으로 출력해서 105 | // 39부터 30까지 가져와보도록 하겠습니다. pagerequest끝에 sort객체를 넣어주면 됩니다. 106 | Sort sort = new Sort(Direction.DESC, "id"); 107 | pageable = new PageRequest(0, 10, sort); 108 | ones = repository.findAll(pageable); 109 | onesList = ones.getContent(); 110 | for (int i = 39, j = 0; i >= 30 ; i--,j++) { 111 | assertEquals(onesList.get(j).getMessage(), HELLO_WORLD+i); 112 | } 113 | } 114 | 115 | @Test 116 | public void 특정메시지로_가져오기() throws Exception { 117 | JustOne one = repository.findByMessage(HELLO_WORLD); 118 | assertNotNull(one); 119 | assertEquals(one.getMessage(), HELLO_WORLD); 120 | } 121 | 122 | @Test 123 | public void 날짜이전_특정메시지로찾기() throws Exception { 124 | repository.deleteAll(); 125 | /**주의 * 자바 날짜는 자바8, joda time 같은 걸로 해주는게 더 좋다고 합니다. 126 | * 여기선 그냥 간단하게 java date 로 이미 가버렸습니다;; 삐질 */ 127 | //먼저 데이터를 삽입하고 128 | Calendar calendar; 129 | for(int i=0;i<10;i++){ 130 | calendar = new GregorianCalendar(2010+i,1,1,13,24,56); 131 | JustOne one = new JustOne(); 132 | one.setDateJoin(calendar.getTime()); 133 | one.setMessage(i%2==0? HELLO_WORLD: _1234); 134 | repository.save(one); 135 | } 136 | //기준 데이터를 가져와서 특정날짜이전과 해당 메시지에 해당하는 리스트를 뽑아봅니다. 137 | calendar = new GregorianCalendar(2015,1,1,13,24,56); 138 | List getList = 139 | repository.findBydateJoinBeforeAndMessage(calendar.getTime(), HELLO_WORLD); 140 | //그리고 검사 141 | int year=2010; 142 | for (JustOne justOne : getList) { 143 | calendar.set(year,1,1,13,24,56); 144 | assertEquals(justOne.getMessage(), HELLO_WORLD); 145 | assertEquals(justOne.getDateJoin(), calendar.getTime()); 146 | year+=2; 147 | } 148 | } 149 | 150 | 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/test/java/com/example/mapping/manytomany/BookRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.manytomany; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.SpringApplicationConfiguration; 7 | import org.springframework.test.context.ActiveProfiles; 8 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 | 10 | import com.example.App; 11 | import com.example.r_mapping.manytomany.Book; 12 | import com.example.r_mapping.manytomany.BookRepository; 13 | import com.example.r_mapping.manytomany.Category; 14 | import com.example.r_mapping.manytomany.CategoryRepository; 15 | 16 | @RunWith(SpringJUnit4ClassRunner.class) 17 | @SpringApplicationConfiguration(classes=App.class) 18 | @ActiveProfiles("test") 19 | public class BookRepositoryTest { 20 | @Autowired BookRepository repoBook; 21 | @Autowired CategoryRepository repoCate; 22 | 23 | @Test 24 | public void testName() throws Exception { 25 | Book book = new Book("MB의 비용"); 26 | Book book1 = new Book("기획된"); 27 | Book book2 = new Book("잡놈들"); 28 | Book book3 = new Book("소탕하라"); 29 | 30 | Category category = new Category(); 31 | category.setName("정치비평에세이"); 32 | category.getBooks().add(book); 33 | category.getBooks().add(book1); 34 | category.getBooks().add(book2); 35 | category.getBooks().add(book3); 36 | 37 | repoBook.save(book); 38 | repoBook.save(book1); 39 | repoBook.save(book2); 40 | repoBook.save(book3); 41 | repoCate.save(category); 42 | } 43 | 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/example/mapping/onetoone/MemberRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.onetoone; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import javax.transaction.Transactional; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.SpringApplicationConfiguration; 11 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 | 13 | import com.example.App; 14 | import com.example.r_mapping.onetoone.Member; 15 | import com.example.r_mapping.onetoone.MemberDetail; 16 | import com.example.r_mapping.onetoone.MemberRepository; 17 | 18 | @RunWith(SpringJUnit4ClassRunner.class) 19 | @SpringApplicationConfiguration(classes=App.class) 20 | @Transactional 21 | public class MemberRepositoryTest { 22 | 23 | @Autowired MemberRepository repository; 24 | 25 | @Test 26 | public void test() { 27 | Member member = new Member(); 28 | member.setName("arahansa"); 29 | 30 | MemberDetail memberDetail = new MemberDetail(); 31 | memberDetail.setAddress("incheon"); 32 | 33 | member.setMemberDetail(memberDetail); 34 | 35 | repository.save(member); 36 | assertEquals(repository.count(), 1); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/example/mapping/secondary/SecondarymasterTest.java: -------------------------------------------------------------------------------- 1 | package com.example.mapping.secondary; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.List; 6 | 7 | import javax.transaction.Transactional; 8 | 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.test.SpringApplicationConfiguration; 14 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 | 16 | import com.example.App; 17 | import com.example.mapping.secondary.SecondaryRepository; 18 | import com.example.mapping.secondary.Secondarymaster; 19 | @RunWith(SpringJUnit4ClassRunner.class) 20 | @SpringApplicationConfiguration(classes=App.class) 21 | @Transactional 22 | public class SecondarymasterTest { 23 | 24 | @Autowired SecondaryRepository repository; 25 | 26 | @Before 27 | public void setup(){ 28 | Secondarymaster master = new Secondarymaster(); 29 | master.setSub1("hello"); 30 | master.setSub2("world"); 31 | 32 | repository.save(master); 33 | } 34 | 35 | @Test 36 | public void test() 37 | { 38 | Secondarymaster getMasters =repository.findBySub2("world"); 39 | System.out.println("lazy loading?"); 40 | System.out.println("master :"+getMasters.getSub2()); 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /target/m2e-wtp/web-resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Implementation-Title: LearnSpringDataJpa Maven Webapp 3 | Implementation-Version: 0.0.1-SNAPSHOT 4 | Built-By: arahansa 5 | Implementation-Vendor-Id: com.example 6 | Build-Jdk: 1.8.0_45 7 | Created-By: Maven Integration for Eclipse 8 | Implementation-Vendor: Pivotal Software, Inc. 9 | Main-Class: com.springcamp.env.SampleProfileApplication 10 | 11 | -------------------------------------------------------------------------------- /target/m2e-wtp/web-resources/META-INF/maven/com.example/LearnSpringDataJpa/pom.properties: -------------------------------------------------------------------------------- 1 | #Generated by Maven Integration for Eclipse 2 | #Fri Jul 10 01:25:24 KST 2015 3 | version=0.0.1-SNAPSHOT 4 | groupId=com.example 5 | m2e.projectName=LearnSpringDataJpa 6 | m2e.projectLocation=C\:\\Users\\arahansa\\workspace\\LearnSpringDataJpa 7 | artifactId=LearnSpringDataJpa 8 | -------------------------------------------------------------------------------- /target/m2e-wtp/web-resources/META-INF/maven/com.example/LearnSpringDataJpa/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.example 5 | LearnSpringDataJpa 6 | war 7 | 0.0.1-SNAPSHOT 8 | LearnSpringDataJpa Maven Webapp 9 | http://maven.apache.org 10 | 11 | 12 | UTF-8 13 | com.springcamp.env.SampleProfileApplication 14 | 1.7 15 | 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-parent 21 | 1.2.5.RELEASE 22 | 23 | 24 | 25 | 26 | org.apache.maven.plugins 27 | maven-resources-plugin 28 | 2.4.3 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-data-jpa 41 | 42 | 43 | javax.servlet 44 | jstl 45 | 46 | 47 | 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 56 | 57 | 58 | 59 | 60 | joda-time 61 | joda-time 62 | 2.5 63 | 64 | 65 | joda-time 66 | joda-time-jsptags 67 | 1.1.1 68 | 69 | 70 | org.jadira.usertype 71 | usertype.spi 72 | 3.0.0.GA 73 | 74 | 75 | 76 | org.jadira.usertype 77 | usertype.core 78 | 3.0.0.GA 79 | 80 | 81 | 82 | 83 | 84 | mysql 85 | mysql-connector-java 86 | 87 | 88 | com.h2database 89 | h2 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | LearnSpringDataJpa 101 | 102 | 103 | 104 | org.apache.maven.plugins 105 | maven-compiler-plugin 106 | 107 | 1.8 108 | 1.8 109 | 110 | 111 | 112 | 113 | 114 | --------------------------------------------------------------------------------