gpt4 book ai didi

hibernate - 如何使用 hibernate 生成自定义 ID,而它必须是表的主键

转载 作者:IT老高 更新时间:2023-10-28 13:51:27 28 4
gpt4 key购买 nike

这是我的 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

最佳答案

谢谢大家的回复......最后我在我的 Department 类中做了一些改变,并使用了一个类来生成 ids........这是我的代码

@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

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 - 如何使用 hibernate 生成自定义 ID,而它必须是表的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158509/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com