【发布时间】:2016-11-21 21:59:56
【问题描述】:
在研究 Hibernate / JPA / ORM 时,我从网上找到了一个 HibernateHelloWorld Java 应用程序。
通过 Maven,我使用这些库:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.15.0</version>
</dependency>
[1] 运行应用程序时,我的第一个问题是无法创建表。好的,我创建了表。
[2] 第二个问题是无法完成提交。
[3] 第三个问题是数据库一直被锁定。
休眠配置文件为:
<?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-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:mydb.db</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="nl.deholtmans.HibernateHelloWorld.Contact"/>
</session-factory>
</hibernate-configuration>
带注解的POJO是:
@Entity
@Table(name = "contact")
public class Contact {
private Integer id;
private String name;
private String email;
public Contact() {
}
public Contact(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Id
public Integer getId() {
return this.id;
}
// etc.
简单的 HibernateHelloWorld 应用是这样的:
public class App {
private static SessionFactory sessionFactory = null;
private static SessionFactory configureSessionFactory() throws HibernateException {
sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
return sessionFactory;
}
public static void main(String[] args) {
configureSessionFactory();
Session session = null;
Transaction tx=null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
Contact myContact = new Contact(202, "My Name", "my_email@email.com");
Contact yourContact = new Contact(203, "Your Name", "your_email@email.com");
session.save(myContact);
session.save(yourContact);
session.flush();
tx.commit();
List<Contact> contactList = session.createQuery("from Contact").list();
for (Contact contact : contactList) {
System.out.println("Id: " + contact.getId() + " | Name:" + contact.getName() + " | Email:" + contact.getEmail());
}
} catch (Exception ex) {
ex.printStackTrace();
tx.rollback();
} finally{
if(session != null) {
session.close();
}
}
}
}
【问题讨论】:
-
我注意到您的代码的第一件事是没有映射文件。通常,休眠应用程序将具有 hibernate.hbm.xml 文件。此文件被传递到configure() methods of the Configuration class 之一。
-
Consider looking at this post 开始了解 Hibernate 如何为您生成数据库模式。它不会自动执行。
-
为简洁起见,我跳过了 Contact.java (POJO) 和休眠配置文件。现在已添加它们。
标签: java hibernate sqlite jdbc