使用基于文件的数据库与Hibernate和Spring

时间:2015-11-20 22:06:16

标签: java spring hibernate spring-mvc

我正在尝试使用Spring 4编写Spring MVC Web应用程序,其中Hibernate 5作为基于文件的数据库的ORM,例如H2或HSQLDB。我遇到的问题是在杀死应用程序时数据不会持久存储到数据库中。对我来说更令人费解的是,在直接打开H2数据文件后,我可以看到我的一些数据。但是,在重新部署应用程序时,我的查询无法获取它。

我应该澄清一点,这不是一个生产应用程序,而是一个旨在实现可移植性的教育演示,因此基于文件是最简单的。

以下是我的一些应用程序代码:

的src /主/资源/ 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-factovry>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.H2Dialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>



    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>
</session-factory>

的src /主/资源/ app.properties

# Package where our entities are located
entity.package = com.sample.hibernate.model

# Details for our datasource
db.driver = org.h2.Driver
db.url = jdbc:h2:file:./src/main/resources/data/sample
db.username =
db.password =

的src /主/ JAVA / COM /样品/休眠/ AppConfig.java

package com.sample.hibernate;

import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.sql.DataSource;

@EnableAutoConfiguration
@ComponentScan
@PropertySource("app.properties")
public class AppConfig implements CommandLineRunner {
    @Autowired
    private SpringTemplateEngine templateEngine;

    @Autowired
    private ApplicationContext context;

    @Autowired
    private Environment env;

    @Value("${db.driver}")
    private String driver;

    @Value("${db.url}")
    private String url;

    @Value("${db.username}")
    private String username;

    @Value("${db.password}")
    private String password;

    @Value("${entity.package}")
    private String entityPackage;

    public static void main(String[] args) {
        SpringApplication.run(AppConfig.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        templateEngine.addDialect(new Java8TimeDialect());
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        Resource config = context.getResource("classpath:hibernate.cfg.xml");
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setConfigLocation(config);
        sessionFactory.setPackagesToScan(entityPackage);
        sessionFactory.setDataSource(dataSource());
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

的src /主/ JAVA / COM /样品/休眠/ DAO / HibernateDao.java

package com.sample.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public abstract class HibernateDao<E> {
    @Autowired
    private SessionFactory sessionFactory;

    public void save(E entity) {
        try {
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.saveOrUpdate(entity);
            session.getTransaction().commit();
            session.close();
        } catch (HibernateException e) {
            System.err.printf("Save failed: %s%n", e);
        }
    }

    public void delete(E entity) {
        try {
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.delete(entity);
            session.getTransaction().commit();
            session.close();
        } catch (HibernateException e) {
            System.err.printf("Delete failed: %s%n", e);
        }
    }

    public List<E> findAll(Class clazz) {
        Session session = sessionFactory.openSession();
        List<E> all = session.createCriteria(clazz).list();
        session.close();
        return all;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public abstract List<E> findAll();
}

DAO的接口和实现......

的src /主/ JAVA / COM /样品/休眠/ DAO / CategoryDao.java

package com.sample.hibernate.dao;

import com.sample.hibernate.model.Category;

import java.util.List;

public interface CategoryDao {
    List<Category> findAll();
    Category findById(Long id);
    void save(Category category);
    void delete(Category category);
}

的src /主/ JAVA / COM /样品/休眠/ DAO / CategoryDaoImpl.java

package com.sample.hibernate.dao;

import com.sample.hibernate.dao.CategoryDao;
import com.sample.hibernate.dao.HibernateDao;
import com.sample.hibernate.model.Category;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CategoryDaoImpl extends HibernateDao<Category> implements CategoryDao {

    @Override
    public Category findById(Long id) {
        Session session = getSessionFactory().openSession();
        Category category = (Category)session.get(Category.class,id);
        session.close();
        return category;
    }

    @Override
    public List<Category> findAll() {
        return findAll(Category.class);
    }
}

最后,我使用Spring Boot和Gradle来引导应用程序并在嵌入式Web服务器中运行它。值得注意的是,该应用程序使用MySQL服务器成功保存数据。在此先感谢您的帮助!

0 个答案:

没有答案