如何在java桌面应用程序中使用spring(transactional)和hibernate创建emdedded H2 DB?

时间:2016-10-26 11:25:15

标签: java spring hibernate transactional embedded-database

我正在尝试使用嵌入式h2 db创建一个项目,并使用带有hibernate的spring框架。如果不存在,我的数据库将在初始化时创建。我的开发平台是intellij。

问题在于我运行应用程序时

@Autowired
private IPersonService personService; // comes null?

这是我的课程和配置文件。

myDB.sql:

CREATE TABLE IF NOT EXISTS personel(
id IDENTITY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age VARCHAR(100));

hibernate.properties:

db.driverClassName=org.h2.Driver
db.url=jdbc:h2:~/h2SpringProject/database/SpringSample;mv_store=false;mvcc=false
db.username=admin
db.password=

这是我的hibernate-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">



    <context:component-scan base-package="com.springapp"/>
    <context:annotation-config/>
    <context:property-placeholder location="hibernate.properties"/>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
        <property name="driverClassName" value="${db.driverClassName}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="suppressClose" value="true"/>
    </bean>


    <jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
        <jdbc:script location="myDb.sql"/>
    </jdbc:initialize-database>


    <bean id="hibernateCfgProperties"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">
                    org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
                </prop>
            </props>
        </property>
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties" ref="hibernateCfgProperties"/>
        <property name="packagesToScan" value="com.springapp.model"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

</beans>

人类

@Entity
@Table(name = "personel")
public class Personel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private String age;
.......

一个IPersonDao接口,这里实现了类

@Component
public class PersonelDaoImpl implements IPersonelDao {

    @Autowired
    private SessionFactory sessionFactory;


    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void savePersonel(Personel personel) {
        getCurrentSession().saveOrUpdate(personel);
    }

    @Override
    public void deletePersonel(long id) {
        getCurrentSession().delete(id);
    }

    @Override
    public List<Personel> getPersonels() {
        return getCurrentSession().createQuery("from Personel").list();
    }
}

有一个IPersonService接口,这里实现了类

@Service("PersonelService")
public class PersonelServiceImpl implements IPersonelService {

    @Autowired
    private IPersonelDao personelDao;

    @Override
    @Transactional
    public void savePersonel(Personel personel) {
        personelDao.savePersonel(personel);
    }

    @Override
    @Transactional
    public void deletePersonel(long id) {
        personelDao.deletePersonel(id);
    }

    @Override
    @Transactional
    public List<Personel> getPersonels() {
        return personelDao.getPersonels();
    }
}

这是我的主要课程

public class MainApp {

    private static ApplicationContext applicationContext;

           public static void main(String[] args) {

        applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");

    ForExample a = new ForExample();
    a.execute();
    }
}


@Component
public class ForExample {

    @Autowired
    private IPersonelService personelService;

    public void execute(){
        Personel p = new Personel();
        p.setName("thats Ok!");
        p.setAge("614345");

        personelService.savePersonel(p);
    }
}

1 个答案:

答案 0 :(得分:0)

public class MainApp {


        public static ApplicationContext applicationContext;

        private static IPersonelService personelService;


        public static void main(String[] args) {

            applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");
            personelService = applicationContext.getBean(IPersonelService.class);

            Personel p = new Personel();
            p.setName("thatsOK!");
            p.setAge("614345");

            personelService.savePersonel(p);

        }
    }

由于弹簧在运行时无法识别新的操作符。