wikibook에 spring과 hibernate를 연결하는 작업을 진행한다.
1. maven dependency 설정
최종적으로는 spring web mvc를 사용할 예정이기 때문에, wikibook project에 다음과 같은 dependency를 추가한다.
pom.xml
<!-- spring test jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.2.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- spring web mvc jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- spring orm jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- mysql connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- hibernate jar -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
추가 후, maven eclipse:eclipse goal을 실행해서, eclipse project로 재등록시키고, eclipse에서 refresh를 하면 모든 jar 파일이 올라오는 것을 알 수 있다.
2. entity class 생성
테스트로 Person이라는 객체를 생성한다. 객체 코드는 다음과 같다.
@Entity
@Table(name="PERSON")
public class Person {
@Id
@GeneratedValue
@Column(name="ID")
private Integer id;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="MONEY")
private Double money;
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;
}
}
3. PersonService를 구성한다.
기본적인 CRUD만을 가진 Service로 구성한다.
@Service("personService")
public class PersonService implements IPersonService {
@Resource
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public List<Person> getAll() {
Session session = sessionFactory.openSession();
List<Person> persons = (List<Person>) session.createCriteria(Person.class).list();
return persons;
}
public Person get(Integer id) {
Session session = sessionFactory.openSession();
return (Person) session.get(Person.class, id);
}
public Person add(String firstName, String lastName, Double money) {
Person person = new Person();
person.setFirstName(firstName);
person.setLastName(lastName);
person.setMoney(money);
Session session = sessionFactory.openSession();
session.save(person);
return person;
}
public Person edit(Integer id, String firstName, String lastName, Double money) {
Person person = get(id);
Session session = sessionFactory.openSession();
person.setFirstName(firstName);
person.setLastName(lastName);
person.setMoney(money);
session.update(person);
session.flush();
return person;
}
public void delete(Integer id) {
Person person = get(id);
Session session = sessionFactory.openSession();
session.delete(person);
session.flush();
}
}
4. test code를 작성한다.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/spring-context.xml")
public class PersonServiceTest {
@Autowired
private IPersonService personService;
@Test
public void addPersons() {
for(Integer i = 0 ; i < 10 ; i++) {
String firstName = "FIRST_NAME " + i.toString();
String lastName = "LAST_NAME " + i.toString();
Double money = i.doubleValue();
Person addedPerson = personService.add(firstName, lastName, money);
assertThat(addedPerson.getId(), not(0));
}
}
@Test
public void getPerson() {
addPersons();
Person person = personService.getAll().get(0);
Integer id = person.getId();
assertThat(id, not(0));
Person newPerson = personService.get(id);
assertThat(person.getId(), is(newPerson.getId()));
}
@Test
public void editPerson() {
addPersons();
Person person = personService.getAll().get(0);
Integer id = person.getId();
assertThat(id, not(0));
String editedFirstName = person.getFirstName() + "__edited";
personService.edit(id, editedFirstName, person.getLastName(), person.getMoney());
Person editedPerson = personService.get(id);
assertThat(editedPerson.getFirstName(), is(editedFirstName));
}
@Test
public void deletePerson() {
addPersons();
Person person = personService.getAll().get(0);
Integer id = person.getId();
assertThat(id, not(0));
personService.delete(id);
assertNull(personService.get(id));
}
}
5. test code를 작성하면 maven 설정에 따라, src/test/resources 에 다음 파일들을 위치시킨다.
spring-context.xml : spring bean 설정
spring.properties : spring bean에 설정된 properties 파일
hibernate.cfg.xml : hibernate dialect 등 option 정보
spring-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:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- person Service bean 정의 -->
<bean id="personService" class="com.xyzlast.services.PersonService"/>
<!-- property file load -->
<context:property-placeholder location="spring.properties" />
<!-- sessionFactory 구성 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="com.xyzlast.entities"/>
<!-- MySql dataSource 구성 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${app.jdbc.driverClassName}" />
<property name="url" value="${app.jdbc.url}" />
<property name="username" value="${app.jdbc.username}" />
<property name="password" value="${app.jdbc.password}" />
</bean>
</beans>
spring.properties
# database properties
app.jdbc.driverClassName=com.mysql.jdbc.Driver
app.jdbc.url=jdbc:mysql://localhost:3306/test
app.jdbc.username=root
app.jdbc.password=qwer12#$
#hibernate properties
hibernate.config=hibernate.cfg.xml
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.connection.release_mode">after_transaction</property>
</session-factory>
</hibernate-configuration>
6. 테스트를 실행한다.
eclipse JUnit plugin을 이용하건, maven command를 이용하던, 모든 방법에서 test 가 ok가 나와야지 된다.
다음은 Controller 구성과 REST 서비스를 구현해보도록 한다.