我创建了一个名为“animal”的Hibernate项目,在这个项目中,我使用Hibernate查询语言(HQL)与SQL Server数据库建立连接。在项目中,我将代码组织到包中,包括“DAO”,它包含两个类:“interfaceDAO”和“animalDAO”。后者实现了“interfaceDAO”中定义的方法。 在“animalDAO”中,我实现了几个函数来管理动物数据,包括: Select All(全部选择):选择所有动物记录。按ID选择:通过ID获取特定动物。插入:添加新动物记录。更新:修改现有动物记录。删除:从数据库中删除动物记录。为了方便数据库连接,我创建了一个“hibernate.cfg.xml”配置文件。此外,我还开发了一个“hibernateUtil.java“类来创建“SessionFactory”,这是管理Hibernate会话的关键组件。 最后,我在“test”包中创建了一个主测试类“testAnimal.java”。这个类允许我执行我在“animalDAO”类中定义的函数。尽管已成功连接到数据库并显示菜单,但错误消息仍然存在。
animalDAO class
package DAO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import model.animal;
import util.hibernateUtil;
public class animalDAO implements interfaceDAO<animal> {
@Override
public List<animal> sellectAll() {
List<animal> list = new ArrayList();
try {
SessionFactory sf = hibernateUtil.getSessionFactory();
if (sf != null) {
// open & begin transaction
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
// transaction
String hql = "from animal";
Query q = s.createQuery(hql);
list = q.getResultList();
// comit & close transaction
trans.commit();
sf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@Override
public animal selectByID(animal t) {
List<animal> list = new ArrayList<>();
try {
SessionFactory sf = hibernateUtil.getSessionFactory();
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
String hql = "from animal a where a.id=:id";
Query q = s.createQuery(hql);
q.setParameter("id", t.getId());
list = q.getResultList();
trans.commit();
sf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
if (list.size() > 0) {
return list.get(0);
}else {
return null;
}
}
@Override
public boolean insert(animal t) {
boolean result = false;
try {
SessionFactory sf = hibernateUtil.getSessionFactory();
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
// save: chỉ lưu khi chưa tồn tại
// s.save(t);
//saveOrUpdate: thêm mới khi chưa tồn tại, cập nhật dữ liệu khi đã tồn tại
s.saveOrUpdate(t);
trans.commit();
sf.close();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean update(animal t) {
boolean result = false;
try {
SessionFactory sf = hibernateUtil.getSessionFactory();
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
// save: chỉ lưu khi chưa tồn tại
// s.save(t);
//saveOrUpdate: thêm mới khi chưa tồn tại, cập nhật dữ liệu khi đã tồn tại
s.saveOrUpdate(t);
trans.commit();
sf.close();
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public boolean delete(animal t) {
try (SessionFactory sf = hibernateUtil.getSessionFactory()) {
if (sf != null) {
try(Session s = sf.openSession()){
Transaction trans = s.beginTransaction();
s.delete(t);
trans.commit();
sf.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
hibernateUtil.java
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class hibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Exception e) {
System.out.println("Error");
return null;
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
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-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=animal;encrypt=false;</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">123456789Thien_Phu</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="model.animal"/>
</session-factory>
</hibernate-configuration>
testAnimal.java class
package test;
import java.sql.Date;
import java.util.List;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import DAO.animalDAO;
import model.animal;
import util.hibernateUtil;
public class testAnimal {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SessionFactory sf = hibernateUtil.getSessionFactory();
int choice = 0;
do {
System.out.println("============================== \r\n"
+ "1. Select All \r\n"
+ "2. Select by id \r\n"
+ "3. Insert \r\n"
+ "4. Update \r\n"
+ "5. Delete \r\n");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 0:
System.out.println("exit!");
break;
case 1:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
List<animal> list = ad.sellectAll();
for (animal a : list) {
System.out.println(a);
}
trans.commit();
sf.close();
}
break;
case 2:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("Enter ID: ");
int id = sc.nextInt();
animal a = new animal();
a.setId(id);
animal result = ad.selectByID(a);
System.out.println(result);
trans.commit();
sf.close();
}
break;
case 3:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("Enter animal name: ");
String name = sc.nextLine();
System.out.println("Enter animal date of birth [yyyy MM dd]: ");
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
sc.nextLine();
Date dob = new Date(year - 1900, month - 1, day);
System.out.println("Enter sex/gender [true / false]: ");
boolean sex = sc.nextBoolean();
animal a1 = new animal(name, dob, sex);
ad.insert(a1);
trans.commit();
sf.close();
}
break;
case 4:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("enter new name for animal: ");
String name = sc.nextLine();
System.out.println("Enter new date of birth for animal [xxxx xx xx]: ");
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
sc.nextLine();
Date dob = new Date(year - 1900, month - 1, day);
System.out.println("enter new sex/gender [true / false]: ");
boolean sex = sc.nextBoolean();
System.out.println("Enter ID: ");
int id = sc.nextInt();
animal a2 = new animal(name, dob, sex);
a2.setId(id);
ad.update(a2);
trans.commit();
sf.close();
}
break;
case 5:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("Enter ID: ");
int id = sc.nextInt();
animal a3 = new animal(id);
a3.setId(id);
ad.delete(a3);
trans.commit();
sf.close();
}
break;
default:
break;
}
} while (choice != 0);
}
}
Error log
Sep 06, 2023 9:04:46 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.6.15.Final
Sep 06, 2023 9:04:46 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Sep 06, 2023 9:04:47 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Sep 06, 2023 9:04:47 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;DatabaseName=animal;encrypt=false;]
Sep 06, 2023 9:04:47 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=sa}
Sep 06, 2023 9:04:47 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Sep 06, 2023 9:04:47 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sep 06, 2023 9:04:47 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Sep 06, 2023 9:04:47 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@3b8ec001] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Sep 06, 2023 9:04:48 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
==============================
1. Select All
2. Select by id
3. Insert
4. Update
5. Delete
1
Hibernate: select animal0_.id as id1_0_, animal0_.dateOfBirth as dateofbi2_0_, animal0_.name as name3_0_, animal0_.sex as sex4_0_ from animal animal0_
Sep 06, 2023 9:04:50 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:sqlserver://localhost:1433;DatabaseName=animal;encrypt=false;]
Sep 06, 2023 9:04:50 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections close
ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:sqlserver://localhost:1433;DatabaseName=animal;encrypt=false;
Sep 06, 2023 9:04:50 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl validateConnectionsReturned
ERROR: Connection leak detected: there are 1 unclosed connections!
animal [id=1, name=cat, dateOfBirth=null, sex=false]
animal [id=2, name=fish, dateOfBirth=2003-04-05, sex=true]
animal [id=6, name=carrovet, dateOfBirth=2003-12-02, sex=false]
Exception in thread "main" org.hibernate.TransactionException: Unable to commit against JDBC Connection
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:92)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:282)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at test.testAnimal.main(testAnimal.java:49)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:231)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:1728)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.commit(SQLServerConnection.java:4451)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.commit(SQLServerConnection.java:4432)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:86)
... 3 more
in the error log it said Exception in thread "main" org.hibernate.TransactionException: Unable to commit against JDBC Connection I try may way check all the jdbc connection but still not work
我试着在测试类中改变一些主要的东西,我在循环外创建一个SessionFactory,然后在每种情况下,我打开一个新的会话,开始一个新的事务,在这种情况下也提交和关闭
case 1:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
List<animal> list = ad.sellectAll();
for (animal a : list) {
System.out.println(a);
}
trans.commit();
sf.close();
}
break;
case 2:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("Enter ID: ");
int id = sc.nextInt();
animal a = new animal();
a.setId(id);
animal result = ad.selectByID(a);
System.out.println(result);
trans.commit();
sf.close();
}
break;
case 3:
if (sf != null) {
Session s = sf.openSession();
Transaction trans = s.beginTransaction();
animalDAO ad = new animalDAO();
System.out.println("Enter animal name: ");
String name = sc.nextLine();
System.out.println("Enter animal date of birth [yyyy MM dd]: ");
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
sc.nextLine();
Date dob = new Date(year - 1900, month - 1, day);
System.out.println("Enter sex/gender [true / false]: ");
boolean sex = sc.nextBoolean();
animal a1 = new animal(name, dob, sex);
ad.insert(a1);
trans.commit();
sf.close();
}
break;
但似乎它不会这样工作
1条答案
按热度按时间iibxawm41#
我已经知道错误在哪里了。
因此,错误基于
animalDAO
类。在方法selectAll
,selectByID
,insert
,update
和delete
中,我忘记用try...catch
包围。这是非常重要的一步,以检查方法是否出错。因此,在我包围了try...catch
中的所有方法之后,项目可以正常工作。以下是
animalDAO
类的更新:错误已被修复。谢谢.