休眠持久

时间:2017-10-26 09:23:48

标签: hibernate java-ee

我是Hibernate的新手,我正在尝试通过在线学习自学。我的问题很少,请参阅以下代码:

@WebServlet(urlPatterns = {"/"}, loadOnStartup = 1)
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final Logger logger = Logger.getLogger(RootServlet.class);


@Override
public void init() throws ServletException {
    super.init();
    logger.info("init started");
    // Read the data from a file
    String url = ReadProperties.readProperty("data");

    try {
        InputStream inputStream = new URL(url).openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuffer buffer = new StringBuffer();
        String line = reader.readLine();
        while (line != null) {
            buffer.append(line);
            line = reader.readLine();
        }

        logger.info("parsing data");
        JsonParser parser = new JsonFactory().createParser(buffer.toString());
        if (JsonToken.START_ARRAY != parser.nextToken()) {
            throw new Exception("bad token");
        }

        JsonToken token = parser.nextToken();
        while(token == JsonToken.START_OBJECT) {

            Employee emp = new Employee();

            emp.setFName(parser.nextTextValue());
            emp.setLName(parser.nextTextValue());

            Session session = HibernateUtil.getSessionFactory().openSession();
            try {
                 session.beginTransaction();
                 session.persist(e);        
                 session.getTransaction().commit();
            } catch (ConstraintViolationException ex) {

            }
            session.close();

            token = parser.nextToken();

        }

    } catch (Exception ex) {
        throw new ServletException(ex);
    }      
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
    Session session = HibernateUtil.getSessionFactory().openSession();
    List<Employee> list = session.createCriteria(Employee.class).list();

    for (Employee e : list) {
        response.getWriter().println("First Name " + entity.getFName());
        response.getWriter().println("Last Name " + e.getLName());
    }

}

}

Hibernate配置文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="hibernate.archive.autodetection">class,hbm</property>
    <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="hibernate.connection.username">user</property>
    <property name="hibernate.connection.password">pass</property>
    <property name="hibernate.connection.url">jdbc:hsqldb:mem:db</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <property name="hibernate.jdbc.batch_size">50</property>
    <mapping class="com.waracle.cakemgr.beans.CakeEntity"></mapping>        
</session-factory>

我没有数据库设置,我刚刚在hibernate配置文件中给出了虚拟值,但上面的代码在运行时从文件中读取,看起来好像数据是持久的,而doGet方法也显示了员工名单。 我不明白为什么这个工作,session.persist会不会抛出任何错误?此外,如果我添加另一个具有相同代码的页面,则从此遍历到该页面会导致等待session.persist无休止地完成。

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

因为您使用的是内存数据库:Cluster cluster = CouchbaseCluster.create(“servername”); cluster.authenticate(“userid”, “password”); Bucket bucket = cluster.openBucket(“bucket”);

HSQLDB表示使用内存数据库,而不是任何物理数据库。