복붙노트

[SPRING] 트랜잭션, JavaConfig에 대해 Hibernate Session을 열 수 없음

SPRING

트랜잭션, JavaConfig에 대해 Hibernate Session을 열 수 없음

오류를 찾을 수 없습니다 ((

Spring MVC + Hibernate, JavaConfig

WebAppConfig :

package com.sprhib.init;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;


@Configuration
@ComponentScan("com.sprhib")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class WebAppConfig {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    @Resource
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        sessionFactoryBean.setHibernateProperties(hibProperties());
        return sessionFactoryBean;
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        return properties;  
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

}

사용자

package com.sprhib.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;
    private Integer age;
    private Boolean isAdmin;
    private Timestamp createdDate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Boolean getAdmin() {
        return isAdmin;
    }

    public void setAdmin(Boolean admin) {
        isAdmin = admin;
    }

    public Timestamp getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Timestamp createdDate) {
        this.createdDate = createdDate;
    }
}



package com.sprhib.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;


@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {

        return sessionFactory.getCurrentSession();
    }



    public void addUser(User user) {

        getCurrentSession().save(user);
    }


    public void updateUser(User user) {
        User userUpdate = getUser(user.getId());
        userUpdate.setName(user.getName());
        userUpdate.setAge(user.getAge());
        userUpdate.setAdmin(user.getAdmin());
        userUpdate.setCreatedDate(user.getCreatedDate());
        getCurrentSession().update(userUpdate);
    }


    public User getUser(int id) {

        return (User)getCurrentSession().get(User.class,id);
    }


    public void deleteUser(int id) {
        User user = getUser(id);
        if (user!=null)
            getCurrentSession().delete(user);

    }


    public List<User> getUsers() {
        System.out.println("zzz");
        return getCurrentSession().createQuery("FROM User").list();
    }
}

UserDAOImpl :

package com.sprhib.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;


@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {

        return sessionFactory.getCurrentSession();
    }



    public void addUser(User user) {

        getCurrentSession().save(user);
    }


    public void updateUser(User user) {
        User userUpdate = getUser(user.getId());
        userUpdate.setName(user.getName());
        userUpdate.setAge(user.getAge());
        userUpdate.setAdmin(user.getAdmin());
        userUpdate.setCreatedDate(user.getCreatedDate());
        getCurrentSession().update(userUpdate);
    }


    public User getUser(int id) {

        return (User)getCurrentSession().get(User.class,id);
    }


    public void deleteUser(int id) {
        User user = getUser(id);
        if (user!=null)
            getCurrentSession().delete(user);

    }


    public List<User> getUsers() {

        return getCurrentSession().createQuery("FROM User").list();
    }
}

UserController :

package com.sprhib.controller;
import java.util.List;

import com.sprhib.model.User;
import com.sprhib.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value="/user")
public class UserController  {

    @Autowired
    private UserService userService;

    @RequestMapping(value="/add", method=RequestMethod.GET)
    public ModelAndView addUserPage()
    {
        ModelAndView modelAndView = new ModelAndView("add-user-form");
        modelAndView.addObject("user",new User());
        return modelAndView;
    }

    @RequestMapping(value="/add", method=RequestMethod.POST)
    public ModelAndView addingUser(@ModelAttribute User user) {

        ModelAndView modelAndView = new ModelAndView("home");
        userService.addUser(user);
        String message = "User was successfully added.";
        modelAndView.addObject("message", message);

        return modelAndView;
    }


    @RequestMapping(value="/list")
    public ModelAndView listOfUsers() {
        ModelAndView modelAndView = new ModelAndView("list-of-users");
        List<User> users = userService.getUsers();
        modelAndView.addObject("users", users);
        return modelAndView;
    }

    @RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
    public ModelAndView editUserPage(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView("edit-user-form");
        User user = userService.getUser(id);
        modelAndView.addObject("user",user);
        return modelAndView;
    }

    @RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
    public ModelAndView edditingUser(@ModelAttribute User user, @PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView("home");
        userService.updateUser(user);
        String message = "User was successfully updated.";
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
    public ModelAndView deleteUser(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView("home");
        userService.deleteUser(id);
        String message = "User was successfully deleted.";
        modelAndView.addObject("message", message);
        return modelAndView;
    }

}

application.properties:

#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/test
db.username=root
db.password=root

#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model

브라우저에서 사용자를 얻으려고 할 때 :

이 예제를 보니 ...

해결법

  1. ==============================

    1.당신은 Hibernate 4를 위해 org.springframework.orm.hibernate4.HibernateTransactionManager를 사용한다.이 클래스는 Hibernate 4의 TransactionContext를 사용한다.

    당신은 Hibernate 4를 위해 org.springframework.orm.hibernate4.HibernateTransactionManager를 사용한다.이 클래스는 Hibernate 4의 TransactionContext를 사용한다.

    최대 절전 모드 5를 사용하는 것처럼 보입니다.

    import org.springframework.orm.hibernate4.HibernateTransactionManager;
    import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
    

    이에

    import org.springframework.orm.hibernate5.HibernateTransactionManager;
    import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
    

    물론 해당 Spring 라이브러리를 사용해야한다. 예제 4.2.4.RELEASE.

  2. from https://stackoverflow.com/questions/35439611/could-not-open-hibernate-session-for-transaction-javaconfig by cc-by-sa and MIT license