HIbernate中session的的save方法必须要事务才能插入数据库吗
1个回答
展开全部
drop table if exists clients;
create table clients(
clientId int auto_increment primary key,
clientName varchar(20) not null
);
client.hbm.xml
<class name="org.swq.chapter6.Client" table="clients">
<id name="clientId" column="clientId" type="java.lang.Integer">
<generator class="native"></generator>
</id>
<property name="clientName" type="java.lang.String">
<column name="clientName" length="20"></column>
</property>
</class>
Client类
package org.swq.chapter6;
public class Client {
private Integer clientId;
private String clientName;
public Integer getClientId() {
return clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
}
测试方法:
Session session = getSession();//取得session
Client client = new Client();
client.setClientName("client");
session.save(client); // 保存
session.close();
当不加入事务的时候执行,在控制台打印sql语句:
Hibernate: insert into chapter6.clients (clientName) values (?)
问题1:
但是查询数据库中并没有添加记录?这是为什么?
但是我用sql手动添加数据时候,发现clientId已经自增了,这又是为什么?
测试方法:
Session session = getSession();
tx = session.beginTransaction();
Client client = new Client();
client.setClientName("client");
session.save(client);
tx.commit();
session.close();
附上出处链接;http://www.iteye.com/problems/1176
create table clients(
clientId int auto_increment primary key,
clientName varchar(20) not null
);
client.hbm.xml
<class name="org.swq.chapter6.Client" table="clients">
<id name="clientId" column="clientId" type="java.lang.Integer">
<generator class="native"></generator>
</id>
<property name="clientName" type="java.lang.String">
<column name="clientName" length="20"></column>
</property>
</class>
Client类
package org.swq.chapter6;
public class Client {
private Integer clientId;
private String clientName;
public Integer getClientId() {
return clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
}
测试方法:
Session session = getSession();//取得session
Client client = new Client();
client.setClientName("client");
session.save(client); // 保存
session.close();
当不加入事务的时候执行,在控制台打印sql语句:
Hibernate: insert into chapter6.clients (clientName) values (?)
问题1:
但是查询数据库中并没有添加记录?这是为什么?
但是我用sql手动添加数据时候,发现clientId已经自增了,这又是为什么?
测试方法:
Session session = getSession();
tx = session.beginTransaction();
Client client = new Client();
client.setClientName("client");
session.save(client);
tx.commit();
session.close();
附上出处链接;http://www.iteye.com/problems/1176
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询