Spring数据JPA只有一个复合键自动递增 [英] Spring data JPA only one composite key auto incremented
问题描述
我正在使用MySQL数据库.
I am using MySQL database.
我的表是一个雇员,其中有两个主键,其中一个是自动递增的.
My table is an employee in which there are two primary keys, out of which one is auto incremented.
我的代码是:
@Embeddable
public class EmployeeId implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name = "id", nullable = false)// this i want to increment
private int id;
// I have tried and @GeneratedValue(strategy = GenerationType.IDENTITY),
//@GeneratedValue(strategy = GenerationType.IDENTITY)
//and @GeneratedValue(strategy = GenerationType.TABLE)
//@GeneratedValue(strategy = GenerationType.AUTO, generator = "id") @SequenceGenerator(name = "id", sequenceName = "id")
@Column(name = "gender_key", nullable = false)
private id gender_key;
}
@Entity
@Table(name = "employee")
public class employee {
@EmbeddedId
private EmployeeId employeeId;
private String emp_name;
private String mobile_no;
employee() {
}}
public interface employeeRepository extends
JpaRepository<employee, EmployeeId> {
}
在我的控制器中,我想要在employeeRepository.save(bean)之后的ID;方法,因为我想将该ID保存在其他表中.
In My Controller I want id after employeeRepository.save(bean); method because i want to save that id in different table .
logger.info("id为--->" + id);
logger.info("id is --- > "+id);
但是我总是得到0的id值.
But I am getting always 0 value of id.
如何获取插入到MySQL表中的id的增量值?
How can I get the incremented value of id which is inserted into MySQL table?
请帮助.
提前谢谢.
推荐答案
您是要从原始对象还是从save
方法返回的对象中获取值?假设您具有以下代码:
Are you trying to get the value from your original object or from the object return from the save
method? Let's assume you have the following code:
employeeRepository.save(bean)
int id = bean.getId();
logger.info("id is --- > "+id);
这确实将返回零,因为您的对象没有此信息.如果要获取在数据库上生成的值,则必须执行以下操作:
This will indeed return zero, since your object didn't have this information. If you want to get the value that was generated on the database you have to do the following:
bean = employeeRepository.save(bean)
int id = bean.getId();
logger.info("id is --- > "+id);
这篇关于Spring数据JPA只有一个复合键自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!