简体   繁体   中英

How to save a field to which long id will be converted in spring boot

I followed this link: https://vladmihalcea.com/how-to-map-calculated-properties-with-hibernate-generated-annotation/

Here is my source code:

private String firstName;

private String lastName;

private String middleName1;

private String middleName2;

private String middleName3;

private String middleName4;

private String middleName5;

@Generated( value = GenerationTime.ALWAYS )
@Column(columnDefinition =
    "AS CONCAT(" +
    "   COALESCE(firstName, ''), " +
    "   COALESCE(' ' + middleName1, ''), " +
    "   COALESCE(' ' + middleName2, ''), " +
    "   COALESCE(' ' + middleName3, ''), " +
    "   COALESCE(' ' + middleName4, ''), " +
    "   COALESCE(' ' + middleName5, ''), " +
    "   COALESCE(' ' + lastName, '') " +
    ")")
private String fullName;

It uses other string fields to generate that fullname field.

What i want is something different.

I have an auto increment id field in spring boot class:

private long id //or it can be int, does not matter

I have also another field, which must be unique and alphanumeric.

private String code;

This field will have 6 alphanumeric (upper or lower case does not matter).

Is it possible to save this field auto while a new object created, with such a method?

Long.toString("id_field_value",36);

Actually, it gives:

0 -> 0
1 -> 1
10 -> A

So, when first object is created, id will be 1.

Any suggestion?

Yes, it can be possible.

You can generate your code in a different method, that will return your alphanumeric value and set the code property to the return value of your random method

Try the following annotations on your long field:

@Id   
@GeneratedValue(strategy = GenerationType.AUTO)
@SequenceGenerator(name="id_sequence", sequenceName="id_sequence", allocationSize=1)
private long id

Save this persistence object using hibernate. Make sure you have a sequence with the specified name in your schema.

Schema can be created by:

CREATE SEQUENCE schema_name.id_sequence
    INCREMENT BY 1
    MINVALUE 1
    MAXVALUE 9223372036854775807
    START 1;

You can refer to the link incase you need some referance

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