Home > OS >  Make String as primary key in Spring Boot
Make String as primary key in Spring Boot

Time:10-17

I want to make 'location'(a String) as my primary key for my Spring Boot project, but I'm way too new to Spring Boot and don't know how to implement it. I want to know the annotations that I should use in entities package to make it work without errors. The table is as below:

CREATE TABLE USER 
(
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(20),
EMAIL VARCHAR(20),
PASSWORD VARCHAR(25), 
LOCATION VARCHAR (20) NOT NULL,
PRIMARY KEY (LOCATION),
UNIQUE KEY (EMAIL)
)



CREATE TABLE WANDER
(
 LOCATION VARCHAR(20)  NOT NULL, 
  PLACES_TO_EAT VARCHAR(20)  NOT NULL,
VISIT VARCHAR(20)  NOT NULL,
METRO VARCHAR(20)  NOT NULL,
  PRIMARY KEY (LOCATION)
)

My Entity package looks like this:

User.java:

package com.hashir.smartcity.entities;

import javax.persistence.Entity;


@Entity
public class User {

    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String location;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

Wander.java

package com.hashir.smartcity.entities;

import javax.persistence.Entity;

@Entity
public class Wander{

    private String location;
    private String placesToEat;
    private String visit;
    private String metro;

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPlacesToEat() {
        return placesToEat;
    }

    public void setPlacesToEat(String placesToEat) {
        this.placesToEat = placesToEat;
    }

    public String getVisit() {
        return visit;
    }

    public void setVisit(String visit) {
        this.visit = visit;
    }

    public String getMetro() {
        return metro;
    }

    public void setMetro(String metro) {
        this.metro = metro;
    }

}

CodePudding user response:

Just use @Id annotation. It is not different when using @Id in non-string fields. However, it is a bad practice if you use the location field as your primary key.

CodePudding user response:

you can refer to this doc @Id String location; Link

  • Related