Spring data JPA only one composite key auto increm

2020-06-23 06:12发布

问题:

I am using MySQL database.

My table is an employee in which there are two primary keys, out of which one is auto incremented.

My code is:

@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> {
        }

In My Controller I want id after employeeRepository.save(bean); method because i want to save that id in different table .

logger.info("id is --- > "+id);

But I am getting always 0 value of id.

How can I get the incremented value of id which is inserted into MySQL table?

Please Help.

Thanks in advance.

回答1:

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);