简体   繁体   中英

Can i modify id type in JPA, from “int” to “long” without affecting data in already present table in DB

I am using JPA for db connectivity and i have a class ABC.java and denoting table as ABC , in the ABC class i have id as:-

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;

Now i want to convert it into :-

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;

Can i modify id type in JPA, from int to long without affecting data in already present table in DB. The Table has Id field as Number(10) .

What all modification I am suppose to do ?

It is possible to change the type of an attribute using the attribute converter annotation. In your case this would mean extending AttributeConverter<Long, Integer> and using that converter for your id field:

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Convert(converter = LongToIntConverter.class)
private long id;

However this would throw an exception if the value of your long id exceeds the range of available int values ( 2^31 + 1 ).

To ensure that this never happens, you would have to ensure that the id generation is restricted to this limit.

Edit: Just to ask, why do you want convert the id to a long but keep the database schema the same? I can't see the advantage of doing both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM