本文介绍了如何使用hibernate生成自定义ID,而它必须是表的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的pojo班
@Entity
public class Department {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="Department_Id")
private Integer deptId;
@Column(name="Department_Name",unique=true,nullable=false)
private String deptName;
@Column(name="Department_Description")
@NotNull
private String deptDesc;
//geters and setters
我想要的是department_id必须是这个主键部门表和这个键的条目必须为DEP0001,DEP0002,DEP0003
What i want is that department_id must be primary key of this Department table and entries for this key must be as DEP0001, DEP0002,DEP0003
推荐答案
谢谢大家的回应.... ..
最后,我在我的Department类中做了一些更改,并使用一个类来生成IDS ........这是我的代码
Thank you everyone for your response......finally i have done some changes in my Department class and used a class for generating ids........Here is my code
@Entity
public class Department {
@Id
@GenericGenerator(name = "sequence_dep_id", strategy = "com.xyz.ids.DepartmentIdGenerator")
@GeneratedValue(generator = "sequence_dep_id")
@Column(name="Department_Id")
private String deptId;
@Column(name="Department_Name",unique=true,nullable=false)
private String deptName;
@Column(name="Department_Description")
@NotNull
private String deptDesc;
//getters and setters
DepartmentIdGenerator.java
DepartmentIdGenerator.java
package com.xyz.ids;
import java.io.Serializable;
import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;
public class DepartmentIdGenerator implements IdentifierGenerator{
@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = "DEP";
Connection connection = session.connection();
try {
Statement statement=connection.createStatement();
ResultSet rs=statement.executeQuery("select count(Department_Id) as Id from demo.Department");
if(rs.next())
{
int id=rs.getInt(1)+101;
String generatedId = prefix + new Integer(id).toString();
System.out.println("Generated Id: " + generatedId);
return generatedId;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
这篇关于如何使用hibernate生成自定义ID,而它必须是表的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!