春天的3.1.0版本4.1.2休眠决赛 - 通过标注如何设置属性数据库配置(spring 3.1.0

2019-09-17 22:05发布

我使用的配置,如下面列出的代码。 自动创建/删除功能接缝不工作,因为它应该(它不会创建/维护数据库(dataSource.setConnectionProperties表(hibernateProperties());))

(它的工作原理时,在数据库中已经创建的表?我认为属性不考虑吗?)

配置

package com.parisibw.persistance;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.parisibw.forms.Contact;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {


    @Bean
    public SessionFactory sessionFactory() {
     return new LocalSessionFactoryBuilder(datasource()).addAnnotatedClasses(Account.class, Contact.class).buildSessionFactory();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

    @Bean
    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties.put("hibernate.show_sql", "true");       
        properties.put("hibernate.hbm2ddl.auto", "create");

        //properties.put("hibernate.connection.driver_class", "org.h2.Driver");
        //properties.put("hibernate.connection.url", "jdbc:h2:db/test;CIPHER=AES");
        //properties.put("hibernate.connection.username", "root");
        //properties.put("hibernate.connection.password", "root root");
        //properties.put("hibernate.connection.pool_size", "1");        
        //properties.put("hibernate.format_sql", "true");
        //properties.put("hibernate.use_sql_comments", "true");
        //properties.put("hibernate.c3p0.min_size", "5");
        //properties.put("hibernate.c3p0.max_size", "20");
        //properties.put("hibernate.c3p0.timeout", "300");
        //properties.put("hibernate.c3p0.max_statements", "50");
        //properties.put("hibernate.c3p0.idle_test_period", "3000");
        //properties.put("hibernate.cache.use_second_level_cache", "true");
        //properties.put("hibernate.cache.region.factory_class",
        //"org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
        //properties.put("hibernate.cache.use_query_cache", "true");
        //properties.put("hibernate.cache.use_minimal_puts", "true");
        //properties.put("hibernate.max_fetch_depth", "10");        

        return properties;
    }

    @Bean
    public DataSource datasource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://dbpath");
            dataSource.setUsername("username");
            dataSource.setPassword("password");
            dataSource.setConnectionProperties(hibernateProperties());
            return dataSource;
    }

}

帐户

@Entity @Table(name="T_ACCOUNT")
public class Account {

    @Id 
    private long id;
    @Column
    private double cashBalance;
    @Column
    private String name;

    public long getId() {
          return id;
    }
    public void setId(long id) {
          this.id = id;
    }
    public double getCashBalance() {
          return cashBalance;
    }
    public void setCashBalance(double cashBalance) {
        this.cashBalance = cashBalance;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return  "id: " + id + ", balance: " + cashBalance + ", name: " + name;

    }

测试类

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String homeTest(Model model) {
    Account account = new Account();

    try{    
        sessionFactory = new HibernateConfig().sessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    //account.setId(2);
    account.setName("Marcin");
    account.setCashBalance(1200);
    session.save(account);
    session.getTransaction().commit();
    session.close();

    }catch (Exception e) {
        logger.info(e.toString());
    }

    model.addAttribute("serverTime" );
    return "test";
}

Answer 1:

你通过你的Hibernate属性为您的数据源连接属性。 相反,他们应该传递给SessionFactory的。

@Bean
public SessionFactory sessionFactory() {
 return new LocalSessionFactoryBuilder(datasource())
   .addAnnotatedClasses(Account.class, Contact.class)
   .addProperties(hibernateProperties())
   .buildSessionFactory();
}

见http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/cfg/Configuration.html?is-external=true (用于LocalSessionFactoryBuilder父类)



Answer 2:

我在这里看到的第一个问题是,你明确地创建一个新的HibernateConfig不是允许弹簧自动装配它的。 因此,在您的测试类添加以下属性:

@Autowire
private SessionFactory sessionFactory;

更深层次看,它看起来像你可能需要阅读起来有点伤春IOC因为你还挺做它看起来像你可能有点糊涂了一种奇怪的方式。 你想要做的一切其实是有点儿已经内置弹簧所以你还挺重新发明轮子。 总之,你要创建的新事物实例,而从春季的情况下让他们的所以它现在的方式挂钩的东西放在一起给你。

看看这是如何正在这里做(是的,它有其他的问题,但你应该能够得到的总体思路): 正确的方式在Spring的事务JUnit测试自动装配一个Hibernate的Session



文章来源: spring 3.1.0 Release Hibernate 4.1.2 Final - Database configuration via annotation how to set properties