在 Eclipse 中使用 XML 的 Hibernate 示例
Hibernate 是一个提供了一些抽象层的框架,这意味着程序员不必担心实现,Hibernate 会在内部为您完成实现,例如与数据库建立连接、编写查询以执行 CRUD 操作等。在本文中,让我们看一个在 Eclipse 中使用 XML 和 MySQL 数据库的 Hibernate 示例。
要求:
- 蚀
- 马文
- 休眠
- MySQL
- JDK 6 以后
例子
当我们要检查 maven 类型的项目时,让我们看看pom.xml
XML
4.0.0
com.geeksforgeeks
HibernateSampleExample
jar
1.0-SNAPSHOT
HibernateSampleExample
http://maven.apache.org
junit
junit
3.8.1
test
org.hibernate
hibernate-core
4.3.5.Final
mysql
mysql-connector-java
5.1.6
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.7
Java
import java.util.Date;
// We can check that column name in "GeekUserDetails" is
// matching with each and every field here. It is always good
// to have the same column name and field name here
public class GeekUserDetails {
private int geekUserId;
private String geekUsername;
private int numberOfPosts;
public int getNumberOfPosts() { return numberOfPosts; }
public int getGeekUserId() { return geekUserId; }
public void setGeekUserId(int geekUserId)
{
this.geekUserId = geekUserId;
}
public String getGeekUsername() { return geekUsername; }
public void setGeekUsername(String geekUsername)
{
this.geekUsername = geekUsername;
}
public void setNumberOfPosts(int numberOfPosts)
{
this.numberOfPosts = numberOfPosts;
}
private String createdBy;
private Date createdDate;
public String getCreatedBy() { return createdBy; }
public void setCreatedBy(String createdBy)
{
this.createdBy = createdBy;
}
public Date getCreatedDate() { return createdDate; }
public void setCreatedDate(Date createdDate)
{
this.createdDate = createdDate;
}
}
XML
XML
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/geeksforgeeks
root
XXXX
org.hibernate.dialect.MySQLDialect
true
true
update
Java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory
= buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try {
// We need to create the SessionFactory from
// hibernate.cfg.xml
return new Configuration()
.configure()
.buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might
// be swallowed
// In case of any exception, it has to be
// indicated here
System.err.println(
"SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
Java
import java.util.Date;
import org.hibernate.Session;
public class GeekUserDetailsTest {
public static void main(String[] args) {
// open the session
Session session = HibernateUtil.getSessionFactory().openSession();
// For doing any CRUD operation,
// let us start a transaction
session.beginTransaction();
// Create an object of GeekUserDetails
GeekUserDetails geekUser = new GeekUserDetails();
// Set all the details required
// to insert into the table
geekUser.setGeekUserId(1);
geekUser.setGeekUsername("GeekUser1");
geekUser.setNumberOfPosts(100);
geekUser.setCreatedBy("GeekUser1");
geekUser.setCreatedDate(new Date());
// Just a save statement is enough which
// automatically creates an insert statement
session.save(geekUser);
// commit will help to complete
// the changes in the table
session.getTransaction().commit();
// close the session
session.close();
}
}
对于 Hibernate,我们应该将详细信息保存在“ hibernate.cfg.xml ”文件中,该文件指定放置了哪种数据库及其凭据、所需的驱动程序等。在这个例子中,我们将使用 MySQL,因此
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate 的优点是它将创建数据库表与Java应用程序类文件的映射。这也在 XML 文件中指定。让我们先在 MySQL 中创建一个表
-- Here "geeksforgeeks" is the name of the database
-- "GeekUserDetails" is the name of the table
-- geekUserId is the Primary Key
CREATE TABLE geeksforgeeks.GeekUserDetails (
geekUserId INT (5) NOT NULL,
geekUsername VARCHAR (20) NOT NULL,
numberOfPosts INT(5) NOT NULL,
CREATED_BY VARCHAR (20) NOT NULL,
CREATED_DATE DATE NOT NULL,
PRIMARY KEY ( geekUserId )
)
让我们看看 Hibernate 中的映射文件。即每一列都必须在表和类之间进行映射。首先,让我们为此在Java中创建 POJO(Model class)
Java
import java.util.Date;
// We can check that column name in "GeekUserDetails" is
// matching with each and every field here. It is always good
// to have the same column name and field name here
public class GeekUserDetails {
private int geekUserId;
private String geekUsername;
private int numberOfPosts;
public int getNumberOfPosts() { return numberOfPosts; }
public int getGeekUserId() { return geekUserId; }
public void setGeekUserId(int geekUserId)
{
this.geekUserId = geekUserId;
}
public String getGeekUsername() { return geekUsername; }
public void setGeekUsername(String geekUsername)
{
this.geekUsername = geekUsername;
}
public void setNumberOfPosts(int numberOfPosts)
{
this.numberOfPosts = numberOfPosts;
}
private String createdBy;
private Date createdDate;
public String getCreatedBy() { return createdBy; }
public void setCreatedBy(String createdBy)
{
this.createdBy = createdBy;
}
public Date getCreatedDate() { return createdDate; }
public void setCreatedDate(Date createdDate)
{
this.createdDate = createdDate;
}
}
现在,与 POJO 文件相关的映射文件。
资源/geekuser.hbm.xml
XML
现在,让我们看看主配置文件
资源/hibernate.cfg.xml
XML
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/geeksforgeeks
root
XXXX
org.hibernate.dialect.MySQLDialect
true
true
update
通过“geekuser.hbm.xml”和“hibernate.cfg.xml”创建 MySQL 表和Java类之间的映射后,让我们尝试在表中简单地插入一条记录让我们尝试通过一个Java应用程序文件。我们需要查看某些文件,例如 HibernateUtil。Java我们需要从 hibernate.cfg.xml 创建 SessionFactory。因此,在进入主代码之前,首先必须满足这个 XML 中的所有条目。否则需要提供抛出异常所需的代码。
Java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory
= buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try {
// We need to create the SessionFactory from
// hibernate.cfg.xml
return new Configuration()
.configure()
.buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might
// be swallowed
// In case of any exception, it has to be
// indicated here
System.err.println(
"SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
GeekUserDetailsTest。 Java -> 会话是通过使用 HibernateUtil 创建的。JavaHibernate SessionFactory 有 getCurrentSession()、openSession() 和 openStatelessSession() 三个方法。在我们的代码中,我们使用了 openSession()。如果没有给出,我们将在线程“main” org.hibernate.HibernateException: No CurrentSessionContext 配置中进入异常。对于 openSession(),它将始终打开一个新会话并且必须关闭
Java
import java.util.Date;
import org.hibernate.Session;
public class GeekUserDetailsTest {
public static void main(String[] args) {
// open the session
Session session = HibernateUtil.getSessionFactory().openSession();
// For doing any CRUD operation,
// let us start a transaction
session.beginTransaction();
// Create an object of GeekUserDetails
GeekUserDetails geekUser = new GeekUserDetails();
// Set all the details required
// to insert into the table
geekUser.setGeekUserId(1);
geekUser.setGeekUsername("GeekUser1");
geekUser.setNumberOfPosts(100);
geekUser.setCreatedBy("GeekUser1");
geekUser.setCreatedDate(new Date());
// Just a save statement is enough which
// automatically creates an insert statement
session.save(geekUser);
// commit will help to complete
// the changes in the table
session.getTransaction().commit();
// close the session
session.close();
}
}
一旦这个文件作为“Java应用程序”运行,我们可以看到一条记录被插入到“GeekUserDetails”表中
关于代码的视频解释:
结论
使用 hibernate.cfg.xml(定义数据库 JDBC 详细信息、SQL 方言等的主要 XML 文件)映射表的列和 POJO 类的映射文件。 (这里是 geekuser.hbm.xml)我们可以在 Hibernate 中轻松地完成所有的 CRUD 操作。