1

How can I make sure that only the phone and message are sent to my database because now I also have the ID of each request that was successfully saved. I want to make the phone a unique identifier by which the values for repeats will be compared in the database.

How to make phone as ID.

UserController

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepo userRepo;
    @PostMapping(consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public String createUser(@Valid @RequestBody User requestUserDetails) {
        userRepo.save(requestUserDetails);

        return "The message delivered.";
    }
}

User

    @Entity
@Table(name = "ApiTable", schema = "TestApi")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String phone;

    private String message;


    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMessage() {
        return message;
    }

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

Application

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

UserRepo

public interface UserRepo extends CrudRepository<User, Long> {

}

Blacit
  • 203
  • 3
  • 12
  • Why are you not using an `@EmbeddedId` and `@IdClass` as suggested in a linked by you answer - https://stackoverflow.com/questions/13032948/how-to-create-and-handle-composite-primary-key-in-jpa/13033039#13033039 ? Basically it totally answers to your question. – VadymVL Oct 31 '19 at 09:04
  • Friend, I made edits and still not working. Updated the code in question. – Blacit Oct 31 '19 at 09:25
  • Do you want to have a composite id (two unique identifiers), or have one id, but ensure that `phone` and `message` fields are unique? – VadymVL Oct 31 '19 at 09:40
  • All I need is for the phone to be unique. – Blacit Oct 31 '19 at 09:52
  • 1
    If you need the `phone` to be unique, why just not annotate it with `@Column(unique=true)`. From your code, it looks like you want to use `phone` as an `id` which is completely different thing. – VadymVL Oct 31 '19 at 10:04
  • Yes, indeed, I wanted the identifier to be a unique phone number. For example, to search in my database was by phone, not id (it is generally desirable to remove) – Blacit Oct 31 '19 at 10:05

3 Answers3

1

Here is how to make phone field an Id based on your example:

@Entity
@Table(name = "ApiTable", schema = "TestApi")
public class User {

    @Id   
    private String phone;

    private String message;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMessage() {
        return message;
    }

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

And your repository will look like:

public interface UserRepo extends CrudRepository<User, String> {
}
VadymVL
  • 5,366
  • 3
  • 26
  • 41
  • Are you sure there should be an int here `@Column(nullable = false,unique = true) private int phone; @Column(nullable = false, unique = true) private int message;` if you change to String, then here is such an error: `org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to find properties (phone, message) in entity` – Blacit Oct 31 '19 at 09:49
  • `annotated with @IdClass:com.example.ApiConnect.domain.User` – Blacit Oct 31 '19 at 09:51
  • Sorry, no need `@IdClass` annotation. Check without it please. – VadymVL Oct 31 '19 at 09:58
  • Why `@Column(nullable = false, unique = true) private int phone; @Column(nullable = false, unique = true) private int message;` Specified as an int? And in getter/setter return String. Because of what is highlighted as an error. – Blacit Oct 31 '19 at 10:43
  • It was a typo. Anyway, as you changed your question, I have updated my answer accordingly. – VadymVL Oct 31 '19 at 11:24
  • Friend, I adore you, thank you very much for your help. – Blacit Oct 31 '19 at 11:29
  • One point is unclear why we change Long to String. I have all works and with Long – Blacit Oct 31 '19 at 11:36
  • 1
    Because in the `CrudRepository` you need to specify Java type of the Id field as the second type argument. As previously you had used `Long id` as an Id in your Entity, your repository used `Long` argument. Now Id is a `String phone` that is why you need to use `String` type argument in the `CrudRepository`. You can read about it more here - https://www.baeldung.com/spring-data-repositories – VadymVL Oct 31 '19 at 11:39
0

Simply use @UniqueConstraint in phone,message pair and create a new field for id.

@Entity
@Table(name = "ApiTable", schema = "TestApi",
uniqueConstraints={@UniqueConstraint(columnNames = {"phone" , "message"})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique=true, nullable = false)
    private Long id;

    private String phone;

    private String message;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getMessage() {
        return message;
    }

    public void setLastName(String message) {
        this.message = message;
    }
}
Mounir Messaoudi
  • 343
  • 1
  • 10
  • Made and the error was such: `org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.example.ApiConnect.domain.User` – Blacit Oct 31 '19 at 09:33
  • Check the updated code (id field), and how to generate a primary key on jpa https://thoughts-on-java.org/jpa-generate-primary-keys/ – Mounir Messaoudi Oct 31 '19 at 09:45
0

You didn't add what are the columns for phone and message. Try with this.

@Embeddable
public class KeyUser implements Serializable {

    @Column(name = "Phone", nullable = false)
    private int phone;

    @Column(name = "Message", nullable = false)
    private int message;

    /** getters and setters **/
}
Pramuditha
  • 638
  • 6
  • 8