刚刚接触SSH框架,虽然可能这个框架已经比较过时了,但是个人认为,SSH作为一个成熟的框架,作为框架的入门还是可以的。
马马虎虎学完了Hibernate的基础,总结一点心得之类的。
学习Hibernate的乐观锁时:
【注:代码中有@的可以不用管,这个是注解方式。即直接在类上使用注解,来达到相同的配置效果。】
package hibernate;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "product_")
public class Product {
int id;
String name;
float price;
Category category;
Set users;
int version;
@Column(name = "version")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@Column(name = "users")
public Set getUsers() {
return users;
}
public void setUsers(Set users) {
this.users = users;
}
@Column(name = "category")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "price")
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
【注:version标签必须跟在id标签后面,否则会有错,运行程序会报错,无法读取XML文件。 hibernate需要访问的属性一定要在"类名.hbm.xml"中定义】
public class TestHibernate {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s1 = sf.openSession();
Session s2 = sf.openSession();
s1.beginTransaction();
s2.beginTransaction();
Product p1 = (Product) s1.get(Product.class, 1);
System.out.println("产品原本价格是: " + p1.getPrice());
p1.setPrice(p1.getPrice() + 1000);
Product p2 = (Product) s2.get(Product.class, 1);
p2.setPrice(p2.getPrice() + 1000);
s1.update(p1);
s2.update(p2);
s1.getTransaction().commit();
s2.getTransaction().commit();
Product p = (Product) s1.get(Product.class, 1);
System.out.println("经过两次价格增加后,价格变为: " + p.getPrice());
sf.close();
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
八月 05, 2018 10:49:36 上午 com.mchange.v2.log.MLog
信息: MLog clients using java 1.4+ standard logging.
八月 05, 2018 10:49:38 上午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
八月 05, 2018 10:49:38 上午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@7cf67e4e [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@3c314b76 [ acquireIncrement -> 2, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2x00zq9x27t6vc4ficmh|4d1b0d2a, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 50000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@ce96782d [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 2x00zq9x27t6vc4ficmh|52feb982, jdbcUrl -> jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 2x00zq9x27t6vc4ficmh|4fcd19b3, numHelperThreads -> 3 ]
Hibernate: select product0_.id as id0_0_, product0_.ver as ver0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
产品原本价格是: 10000.0
Hibernate: select product0_.id as id0_0_, product0_.ver as ver0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_, user1_.name as name3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
Hibernate: select products0_.uid as uid3_1_, products0_.pid as pid1_, product1_.id as id0_0_, product1_.ver as ver0_0_, product1_.name as name0_0_, product1_.price as price0_0_, product1_.cid as cid0_0_ from user_product products0_ inner join product_ product1_ on products0_.pid=product1_.id where products0_.uid=?
Hibernate: update product_ set ver=?, name=?, price=?, cid=? where id=? and ver=?
Hibernate: update product_ set ver=?, name=?, price=?, cid=? where id=? and ver=?
Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [hibernate.Product#1]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1950)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2594)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2494)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2821)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at hibernate.TestHibernate.main(TestHibernate.java:404)