Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.setHibernateFlushMode(FlushMode.MANUAL);
Person person = new Person();
person.setFirstName("Java");
person.setLastName("Hibernate");
transaction = session.beginTransaction();
session.save(person);
BigInteger count = (BigInteger) session.createNativeQuery("select count(*) from Person")
.setHibernateFlushMode(FlushMode.MANUAL).getSingleResult();
System.out.println("Total records are= " + count);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
Файл конфигурации Hibernate:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_practice</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="connection.autocommit">false</property>
<mapping class="entities.Person"/>
</session-factory>
</hibernate-configuration>
Я использую режим Hibernate Flu sh в качестве РУЧНОГО. Но метод save выполняет метод вставки, хотя я не вызываю метод session.flu sh (). Я использую hibernate 5.2.12 и mysql dirver 8.0.6
Output is below:
Hibernate:
insert into person (first_name, last_name) values (?, ?)
Hibernate:
select count(*) from Person
Total records are= 5
Класс HibenateUtil ниже:
public class HibernateUtil {
private static StandardServiceRegistry standardServiceRegistry;
private static SessionFactory sessionFactory;
static{
if (sessionFactory == null) {
try {
standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
e.printStackTrace();
if (standardServiceRegistry != null) {
StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
}
}
}
}
//Utility method to return SessionFactory
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Класс HibernateUtil ниже Пожалуйста, помогите мне.