본문 바로가기

Backend/Spring & SpringBoot

[Spring Boot] Spring에서의 Hibernate 사용법

728x90

1. Spring Framework에서 Hibernate 사용

1) Maven Dependency 추가

2) Spring Bean 설정 

3) Entity Bean (with annotation) 

4) DAO Layer ( Spring JDBC => Hibernate)


1) Maven Dependency 추가 

<!– Spring-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${org.springframework-version}</version>
</dependency>

<!– Hibernate ->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.4.28.Final</version>
</dependency>

 

2) hibernate configuartion (dao-context.xml)

- hiberante.cfg.xml 파일을 실제로 생성할 필요가 없고, dao-context.xml에 정보를 넣어주면된다.

- Configuring DataSource Bean

<context:property-placeholder location="/WEB-INF/props/jdbc.properties" />

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
		destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
</bean>

<!--Configuring SessionFactory Bean -->

<bean id="sessionFactory"
	class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="packagesToScan">
    <list>
      <value>kr.ac.hansung.cse.model</value> <!-- @Entity라는 어노테이션을 스캔해준다.-->
    </list>
  </property>

  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
      <prop key="hibernate.hbm2ddl.auto">create</prop>
      <prop key="hibernate.show_sql">true</prop>
      <prop key="hibernate.format_sql">false</prop>
    </props>
  </property>
</bean>

<!-- AOP 를 사용하여 transaction이 자동적으로 사용됨. -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<context:annotation-config></context:annotation-config>
<context:component-scan base-package="kr.ac.hansung.cse.dao">
</context:component-scan>

 

 

3) Mapping Model class using Annotations 

Object Tier element Database Tier element
Entity class Database table
Field of entity class Database table column
Entity instance Database table row

# JPA Annotation

JPA annotation Description
@Entity The javax.persistence.Entity annotation declares a class as an entity bean that can be persisted by Hibernate, since Hibernate provides JPA implementation.
@Table The javax.persistence.Table annotation can be used to define table mapping. It provides attributes that allows us to override the table name, its catalogue, and its schema
@Id The javax.persistence.Id annotation is used to define the primary key, and it will automatically determine the appropriate primary key generation strategy to be used
@GeneratedValue
(How to generate primary keys with Hibernate)

The javax.persistence.GeneratedValue annotation provides for the specification of generation strategies for the values of primary keys.
Strategy: AUTO(default), IDENTITY, SEQUENCE, TABLE

@Column

The javax.persistence.Column annotation is used to map the field with the table column
We can also specify length, nullable, and uniqueness for the bean properties

- GenerationType.IDENTITY

- GenerationType.TABLE

 

@GeneratedValue(strategy = GenerationType.AUTO) for MySQL databases

 

- Hibernate 4 selected the GenerationType.IDENTITY 

which uses an autoincremented database column

 

- Hibernate 5 selects the GenerationType.TABLE 

which uses a extra database table to generate primary keys

(‘hibernate_sequence’ table, which shares the next_val across the tables)

 

- MySql doesn't support the standard sequence type natively

 

@Entity
@Table(name="product")
public class Product {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="product_id")
    private int id;

    private String name;
    private String category;
    private double price;
    private String manufacturer;
    private int unitInStock;
    private String description;

    @Transient	//DB에 저장하지않음.
    private MultipartFile productImage;

    private String imageFilename;		//File 경로
}

4. DAO

 

@Repository
@Transactional
public class ProductDao {

	@Autowired
	private SessionFactory sessionFactory;

	public Product getProductById(int id) {
		Session session = sessionFactory.getCurrentSession();
		Product product = (Product) session.get(Product.class, id);

		return product;
	}

	public List<Product> getProducts() {
		Session session = sessionFactory.getCurrentSession();
		String hql = "from Product";

		Query<Product> query = session.createQuery(hql, Product.class);
		List<Product> productList = query.getResultList();

		return productList;
	}

	public void addProduct(Product product) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(product);
		session.flush();
	}

	public void deleteProduct(Product product) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(product);
		session.flush();
	}

	public void editProduct(Product product) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(product);
		session.flush();
	}
}
728x90