一連の記事
-kramsの SpringとHibernateによる翻訳を続けます。
前の記事:
「Spring MVC 3、Hibernateからの注釈、MySQL。 統合チュートリアル 。
」はじめに
このチュートリアルでは、HibernateアノテーションとSpring MVC 3アノテーションを使用して1対多の関係を紹介し、@ OneToManyアノテーションを使用してオブジェクト間の関係を示します。 カスケード型やフェッチ戦略は使用せず、代わりに標準の@OneToMany設定を使用します。
1対多の関連付けとは何ですか?
1対多の関連付けは、テーブルAの各レコードがテーブルBの多くのレコードに対応する場合に発生しますが、テーブルBの各レコードにはテーブルAに対応するレコードが1つしかありません。
アプリケーションの仕様。
アプリケーションは、シンプルなCRUDレコードリスト管理システムです。 各エントリは1人に対応し、個人データとクレジットカード情報が含まれています。 各人は複数のクレジットカードを所有できます。 また、顔とクレジットカードを編集するシステムも追加します。
以下は、将来のアプリケーションのスクリーンショットです。


ドメインオブジェクト仕様に基づいて、人とクレジットカードの2つのドメインオブジェクトがあります。
個人のオブジェクトには次のフィールドが必要です。
-id
-名
-姓(姓)
-お金(お金)
-クレジットカード(クレジットカード)
オブジェクトには、次のクレジットカードフィールドがあります。
-id
-タイプ
-番号
各人には多くのクレジットカードがあるため、1対多の関連付けを使用していることに注意してください。 もちろん、この状況を反対側から見て、多対1の関連付けを使用できますが、これは別のレッスンのトピックになります。
開発開発をドメイン、サービス、コントローラーの3つのレイヤーに分割し、構成ファイルを指定します。
ドメイン層から始めましょう。前述のように、PersonとCreditCardの2つのドメインオブジェクトがあります。 したがって、ドメインレイヤーを表す2つのPOJOを宣言します。 それぞれに、データベースに保存する
エンティティ注釈があります。
Person.javapackage org.krams.tutorial.domain; import java.io.Serializable; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "PERSON") public class Person implements Serializable { private static final long serialVersionUID = -5527566248002296042L; @Id @Column(name = "ID") @GeneratedValue private Integer id; @Column(name = "FIRST_NAME") private String firstName; @Column(name = "LAST_NAME") private String lastName; @Column(name = "MONEY") private Double money; @OneToMany private Set<CreditCard> creditCards; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public Set<CreditCard> getCreditCards() { return creditCards; } public void setCreditCards(Set<CreditCard> creditCards) { this.creditCards = creditCards; } }
PersonクラスはPERSONテーブルにマップされます。 そして、それはこのように見えます:

変数creditCardsのアノテーション@OneToManyに注意してください。カスケード設定もフェッチ戦略もデフォルト設定に依存して指定しませんでした。 後で、これに関連するいくつかの問題を見つけます。
Person.java @Entity @Table(name = "PERSON") public class Person implements Serializable { ... @OneToMany private Set<CreditCard> creditCards; ... }
CreditCard.java package org.krams.tutorial.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "CREDIT_CARD") public class CreditCard implements Serializable { private static final long serialVersionUID = 5924361831551833717L; @Id @Column(name = "ID") @GeneratedValue private Integer id; @Column(name = "TYPE") private String type; @Column(name = "NUMBER") private String number; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
CreditCardクラスはCREDIT_CARDテーブルに表示され、次のようになります。

phpmyadmin dbデザイナーを使用して、PersonとCreditCardの関係を見てみましょう。

生成されたテーブルを見てください。

CreditCardとPersonの2つのエンティティのみを指定し、データベースには2つのテーブルのみが表示されると予想しました。 では、なぜ3つあるのでしょうか? 3番目のリンクテーブルはデフォルト設定で作成されるため。
Hibernate Annotationsリファレンスガイドからの引用:
マッピングの説明がない場合、1対多の関係にリンクテーブルが使用されます。 テーブルの名前は、最初のテーブルの名前、文字「_」、2番目のテーブルの名前を連結したものです。 1対多の比率を確保するために、UNIQUE修飾子が最初のテーブルのIDを持つ列に割り当てられます。
後でデフォルト設定のその他の欠点について説明します。
サービス層。ドメインオブジェクトを宣言したら、PersonServiceとCreditCardServiceの2つのサービスを含むサービスレイヤーを作成する必要があります。
PersonServiceは、PersonエンティティのCRUD操作を処理します。 各メソッドは最終的にHibernateオブジェクトをセッションに渡します。
PersonService.java package org.krams.tutorial.service; import java.util.List; import java.util.Set; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.krams.tutorial.domain.CreditCard; import org.krams.tutorial.domain.Person; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("personService") @Transactional public class PersonService { protected static Logger logger = Logger.getLogger("service"); @Resource(name="sessionFactory") private SessionFactory sessionFactory; public List<Person> getAll() { logger.debug("Retrieving all persons");
PersonServiceは非常に単純で、特に注意が必要な2つの主な問題を解決します。
問題1.フェッチ戦略
個人の記録を受信しても、それに関連付けられたクレジットカードの記録は読み込まれません。
次の要求はIDによって個人によって受信されます。
クエリquery = session.createQuery( "FROM Person WHERE p.id =" + id);この問題は、@ OneToManyアノテーションを説明するときにフェッチ戦略を指定しなかったために発生します。これを修正するために、リクエストを変更します。
クエリquery = session.createQuery( "FROM Person as p LEFT JOIN FETCH p.creditCards WHERE p.id =" + id);問題2.カスケード型。
人を削除しても、対応するクレジットカードは削除されません。
次のエントリは、顔エントリを削除します。
session.delete(人);この問題は、@ OneToManyアノテーションでカスケード型を指定しなかったために発生します。 これは、クレジットカードのエントリを削除する戦略を実装する必要があることを意味します。
まず、クレジットカードのリクエストを作成する必要があります。これは、コレクションに一時的に保管するために使用します。 次に、個人レコードを削除します。 コレクションからすべてを抽出した後、1つ1つを削除します。
CreditCardServiceCreditCardServiceは、CreditCardエンティティでのCRUD操作の処理を担当します。 各メソッドは最終的にHibernateオブジェクトをセッションに渡します。
CreditCardService.java package org.krams.tutorial.service; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.krams.tutorial.domain.CreditCard; import org.krams.tutorial.domain.Person; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("creditCardService") @Transactional public class CreditCardService { protected static Logger logger = Logger.getLogger("service"); @Resource(name="sessionFactory") private SessionFactory sessionFactory; public List<CreditCard> getAll(Integer personId) { logger.debug("Retrieving all credit cards");
delete()メソッドに特に注意してください:
削除() public void delete(Integer id) { logger.debug("Deleting existing credit card");
クレジットカードを削除するには、最初に次のクエリを使用してリンクテーブルからクレジットカードを削除する必要があります。
クエリquery = session.createSQLQuery( "DELETE FROM PERSON_CREDIT_CARD" +
"WHERE creditCards_ID =" + id);スパニングテーブルは、HQLではなく、HibernateとSQLクエリによって作成されることに注意してください。
リンクテーブルからデータを削除した後、CREDIT_CARDテーブルから情報を削除します。
session.delete(creditCard)コントローラー層。サービス層とドメイン層を作成したら、コントローラー層を作成する必要があります。 MainControllerとCreditCardControllerの2つのコントローラーを作成します。
メインコントローラーMainControllerは、エンティティレコードの要求を処理します。 各CRUD要求は最終的にPersonServiceに渡され、対応するJSPページを返します。
MainController.java package org.krams.tutorial.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.krams.tutorial.domain.Person; import org.krams.tutorial.dto.PersonDTO; import org.krams.tutorial.service.CreditCardService; import org.krams.tutorial.service.PersonService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/main/record") public class MainController { protected static Logger logger = Logger.getLogger("controller"); @Resource(name="personService") private PersonService personService; @Resource(name="creditCardService") private CreditCardService creditCardService; @RequestMapping(value = "/list", method = RequestMethod.GET) public String getRecords(Model model) { logger.debug("Received request to show records page");
getRecords()メソッドはPersonとCreditCardをデータ転送オブジェクトPersonDTOとして表示することに注意してください。
getRecords() @RequestMapping(value = "/list", method = RequestMethod.GET) public String getRecords(Model model) { logger.debug("Received request to show records page");
PersonDTOは、records.jspのデータモデルとして機能します。
PersonDTO.java package org.krams.tutorial.dto; import java.util.List; import org.krams.tutorial.domain.CreditCard; public class PersonDTO { private Integer id; private String firstName; private String lastName; private Double money; private List<CreditCard> creditCards; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public List<CreditCard> getCreditCards() { return creditCards; } public void setCreditCards(List<CreditCard> creditCards) { this.creditCards = creditCards; } }
CreditCardControllerCreditCardControllerは、クレジットカードのリクエストを処理します。 このコントローラーで使用可能なすべてのメソッドを使用するわけではありません;完全を期すために追加されています。
CreditCardController.java package org.krams.tutorial.controller; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.krams.tutorial.domain.CreditCard; import org.krams.tutorial.service.CreditCardService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/main/creditcard") public class CreditCardController { protected static Logger logger = Logger.getLogger("controller"); @Resource(name="creditCardService") private CreditCardService creditCardService; @RequestMapping(value = "/add", method = RequestMethod.GET) public String getAdd(@RequestParam("id") Integer personId, Model model) { logger.debug("Received request to show add page");
VIEWレイヤー。ドメイン、サービス、およびコントローラーレイヤーについて説明した後、VIEWレイヤーを作成します。 主にJSPページで構成されます。 ここにあります:

records.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Records</h1> <c:url var="editImgUrl" value="/resources/img/edit.png" /> <c:url var="deleteImgUrl" value="/resources/img/delete.png" /> <c:url var="addUrl" value="/krams/main/record/add" /> <table style="border: 1px solid; width: 100%; text-align:center"> <thead style="background:#d3dce3"> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Money</th> <th colspan="2"></th> <th>CC Type</th> <th>CC Number</th> <th colspan="3"></th> </tr> </thead> <tbody style="background:#ccc"> <c:forEach items="${persons}" var="person"> <c:url var="editUrl" value="/krams/main/record/edit?id=${person.id}" /> <c:url var="deleteUrl" value="/krams/main/record/delete?id=${person.id}" /> <c:if test="${!empty person.creditCards}"> <c:forEach items="${person.creditCards}" var="creditCard"> <tr> <td><c:out value="${person.id}" /></td> <td><c:out value="${person.firstName}" /></td> <td><c:out value="${person.lastName}" /></td> <td><c:out value="${person.money}" /></td> <td><a href="${editUrl}"><img src="${editImgUrl}"></img></a></td> <td><a href="${deleteUrl}"><img src="${deleteImgUrl}"></img></a></td> <td><c:out value="${creditCard.type}" /></td> <td><c:out value="${creditCard.number}" /></td> <c:url var="addCcUrl" value="/krams/main/creditcard/add?id=${person.id}" /> <c:url var="editCcUrl" value="/krams/main/creditcard/edit?pid=${person.id}&cid=${creditCard.id}" /> <c:url var="deleteCcUrl" value="/krams/main/creditcard/delete?id=${creditCard.id}" /> <td><a href="${addCcUrl}">+</a></td> <td><a href="${editCcUrl}"><img src="${editImgUrl}"></img></a></td> <td><a href="${deleteCcUrl}"><img src="${deleteImgUrl}"></img></a></td> </tr> </c:forEach> </c:if> <c:if test="${empty person.creditCards}"> <tr> <td><c:out value="${person.id}" /></td> <td><c:out value="${person.firstName}" /></td> <td><c:out value="${person.lastName}" /></td> <td><c:out value="${person.money}" /></td> <td><a href="${editUrl}"><img src="${editImgUrl}"></img></a></td> <td><a href="${deleteUrl}"><img src="${deleteImgUrl}"></img></a></td> <td>N/A</td> <td>N/A</td> <c:url var="addCcUrl" value="/krams/main/creditcard/add?id=${person.id}" /> <td><a href="${addCcUrl}">+</a></td> <td></td> <td></td> </tr> </c:if> </c:forEach> </tbody> </table> <c:if test="${empty persons}"> No records found. </c:if> <p><a href="${addUrl}">Create new record</a></p> </body> </html>
新しいエントリを追加

add-record.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Create New Record</h1> <c:url var="saveUrl" value="/krams/main/record/add" /> <form:form modelAttribute="personAttribute" method="POST" action="${saveUrl}"> <table> <tr> <td><form:label path="firstName">First Name:</form:label></td> <td><form:input path="firstName"/></td> </tr> <tr> <td><form:label path="lastName">Last Name</form:label></td> <td><form:input path="lastName"/></td> </tr> <tr> <td><form:label path="money">Money</form:label></td> <td><form:input path="money"/></td> </tr> </table> <input type="submit" value="Save" /> </form:form> </body> </html>
既存のエントリの編集:

edit-record.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Edit Existing Record</h1> <c:url var="saveUrl" value="/krams/main/record/edit?id=${personAttribute.id}" /> <form:form modelAttribute="personAttribute" method="POST" action="${saveUrl}"> <table> <tr> <td><form:label path="id">Id:</form:label></td> <td><form:input path="id" disabled="true"/></td> </tr> <tr> <td><form:label path="firstName">First Name:</form:label></td> <td><form:input path="firstName"/></td> </tr> <tr> <td><form:label path="lastName">Last Name</form:label></td> <td><form:input path="lastName"/></td> </tr> <tr> <td><form:label path="money">Money</form:label></td> <td><form:input path="money"/></td> </tr> </table> <input type="submit" value="Save" /> </form:form> </body> </html>
新しいクレジットカードを追加します。

add-credit-card.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Add New Credit Card</h1> <c:url var="saveUrl" value="/krams/main/creditcard/add?id=${personId}" /> <form:form modelAttribute="creditCardAttribute" method="POST" action="${saveUrl}"> <table> <tr> <td>Person Id:</td> <td><input type="text" value="${personId}" disabled="true"/> </tr> <tr> <td><form:label path="type">Type:</form:label></td> <td><form:input path="type"/></td> </tr> <tr> <td><form:label path="number">Number:</form:label></td> <td><form:input path="number"/></td> </tr> </table> <input type="submit" value="Save" /> </form:form> </body> </html>
既存のクレジットカードを編集:

edit-credit-card.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Edit Existing Credit Card</h1> <c:url var="saveUrl" value="/krams/main/creditcard/edit?id=${creditCardAttribute.id}" /> <form:form modelAttribute="creditCardAttribute" method="POST" action="${saveUrl}"> <table> <tr> <td>Person Id:</td> <td><input type="text" value="${personId}" disabled="true"/> </tr> <tr> <td><form:label path="type">Type:</form:label></td> <td><form:input path="type"/></td> </tr> <tr> <td><form:label path="number">Number:</form:label></td> <td><form:input path="number"/></td> </tr> </table> <input type="submit" value="Save" /> </form:form> </body> </html>
構成。必要なすべてのJavaクラスを作成しました。 次のステップは、必要な構成ファイルを作成することです。
web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/krams/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
spring-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans>
applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="org.krams.tutorial" /> <mvc:annotation-driven /> <import resource="hibernate-context.xml" /> </beans>
hibernate-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:property-placeholder location="/WEB-INF/spring.properties" /> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="${hibernate.config}" p:packagesToScan="org.krams.tutorial"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${app.jdbc.driverClassName}" p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}" p:acquireIncrement="5" p:idleConnectionTestPeriod="60" p:maxPoolSize="100" p:maxStatements="50" p:minPoolSize="10" /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> </beans>
hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> </session-factory> </hibernate-configuration>
spring.properties # database properties app.jdbc.driverClassName=com.mysql.jdbc.Driver app.jdbc.url=jdbc:mysql://localhost/mydatabase app.jdbc.username=root app.jdbc.password= #hibernate properties hibernate.config=/WEB-INF/hibernate.cfg.xml
アプリケーションの起動。データベースをインストールします。
このアプリケーションでは、MySQLをデータベースとして使用しています。 アプリケーションを起動するには、データベースが作成されていることを確認してください。
作成するには、次の手順を実行します。
1. phpmyadmin(または他の任意のデータベースプログラム)を開きます
2.新しいmydatabaseを作成する
3.アプリケーションを実行すると、データベーススキーマが自動的に作成されます。
確認するには、アプリケーションのWEB_INFディレクトリにあるmydatabase.sqlファイルを使用します。
アプリケーションにアクセスするには、次のURLを使用します。
ローカルホスト :8080 / spring-hibernate-one-to-many-default / krams / main / record / list
おわりに1対多の関係とHibernateアノテーションを使用して、Spring MVCアプリケーションを作成しました。 また、@ OneToManyアノテーションのデフォルト設定に関連する問題についても説明しました。
GIT:
github.com/sa4ek/spring-hibernate-one-to-many-default