我正在开发一个个人项目,我有多个线程调用 DAO 中的方法 save,执行该方法的第一个线程工作正常,但第二个线程在执行 save 方法中的增强 for 时停止,并且不来后退。我是否必须在 java 代码/hibernate 中进行一些操作,或者这是我的 MariaDB 的配置? (观察:寄存器列表有大约100个寄存器,我保存它时,我不知道这是否与我必须保存的数据量有关)。
DAO上的保存方法:
`public synchronized void save(List<Registers> registers) throws Exception {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory(this.url).openSession();
transaction = session.beginTransaction();
for (final Registers register : registers) {
session.save(register);
}
transaction.commit();
} catch (final Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}`
**寄存器类:**
`@SuppressWarnings("serial")
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = "TAB_REGISTERS")
public class Registers implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "COD_REG")
private Long cod;
// The rest of the @columns with the mapped variables and the constructors
}`
我的hibernate.cfg.xml:
`<?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="javax.persistence.jdbc.driver">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.order_updates">true</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">2</property>
<property name="hibernate.c3p0.timeout">100</property>
<property name="hibernate.c3p0.max_statements">1000</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
</session-factory>
</hibernate-configuration>`
Dao上面的调用代码:
public void saveNewRegisters(List<Registers> registers){
try {
this.dao.save(registers);
} catch (final Exception e) {
logger.error("save()", e);
}
}