准备环境:
表:demo_lock
CREATE TABLE `demo_lock` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`aversion` int(12) NOT NULL DEFAULT '0',
`avalue` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of demo_lock
-- ----------------------------
INSERT INTO `demo_lock` VALUES ('1', '0', '0');
`id` int(12) NOT NULL AUTO_INCREMENT,
`aversion` int(12) NOT NULL DEFAULT '0',
`avalue` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of demo_lock
-- ----------------------------
INSERT INTO `demo_lock` VALUES ('1', '0', '0');
映射类:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
/**
* hibernate 乐观锁测试
*
*/
@Entity
@Table(name = "demo_lock")
public class DemoLock implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8908901013537360047L;
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Id
@Column(name = "id", unique = true, nullable = false)
private Integer id;
/**
* 版本号
*/
@Version
@Column(name = "aversion" )
private int aversion;
/**
*
*/
@Column(name = "avalue" )
private int avalue;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getAversion() {
return aversion;
}
public void setAversion(int aversion) {
this.aversion = aversion;
}
public int getAvalue() {
return avalue;
}
public void setAvalue(int avalue) {
this.avalue = avalue;
}
}
DAO:
@Repository
@Scope("prototype")
public class DemoLockDaoImpl extends BaseDAOImpl implements DemoLockDao {
}
Service:
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.gxkj.web.jiancai.daos.DemoLockDao;
import com.gxkj.web.jiancai.entitys.DemoLock;
import com.gxkj.web.jiancai.services.DemoLockService;
@Service
@Scope("prototype")
public class DemoLockServiceImpl implements DemoLockService {
@Autowired
private DemoLockDao demoLockDao;
public DemoLock getDemoLockById(int id) throws SQLException {
return (DemoLock) demoLockDao.selectById(id, DemoLock.class);
}
public void updateDemoLock(DemoLock entity) throws SQLException {
demoLockDao.update(entity);
}
}
注意事项:修改时version是必填参数。