One to one bi direction mapping is not working - spring

My code contains two entities, that have relation with each other.
Student Class :
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "student_detail_id")
private StudentDetail studentDetail;
public Student() {}
//getters setters
StudentDetail Class :
#Entity
#Table(name = "student_detail")
public class StudentDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
public StudentDetail() {}
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
public StudentDetail() {}
Why is the one to one bi direction mapping not working?

In Student_Detail you have to specify #OntToOne Annotation also.
#Entity
#Table(name = "student_detail")
public class StudentDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "college")
private String college;
#Column(name = "no_of_problems_solved")
private int noOfProblemsSolved;
#OneToOne(mappedBy = "studentDetail", cascade = CascadeType.ALL)
private Student student;
//Getters setters
}
This should work for you.

Related

Manytoone mapping for two tables to the single entity

Class A{
private int campid;
private string name;
}
Class B {
Private int campid;
Private string name;
}`
Class combo{
private int id;
private string phonenumber;
}
I'm trying like this
Class A{
private int campid;
private string name;
#OneToMany(targetEntity = Combo.class,mappedBy ="a",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}
Class B {
Private int campid;
Private string name;
#OneToMany(targetEntity = Combo.class,mappedBy ="b",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}`
Class combo{
private int id;
private string phonenumber;
#ManyToOne
#JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private A a;
#ManyToOne
#JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private B b;
}
want to store the campid of class A and campid class B as the foreign key in the combo table. One campid can have multiple phone numbers.
I want to do this in spring jpa..I'm not understanding how to do it
#Entity
#Table(name = "a")
public class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "camp_id")
private Long campid;
#Column(name = "name")
private String name;
#Column
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
#JoinTable(name = "a_combo",
joinColumns = #JoinColumn(name = "camp _id"),
inverseJoinColumns = #JoinColumn(name = "id"))
private Set<Combo> comboSet = new HashSet<>();
}
And same for B class

How to get data from another table

#Entity
#Table(name="driver_duties")
public class Duties{
private String driverId;
private String hubName;
private String vehicleNumber;
// with getter and setters
}
another table
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
// with getter and setters
}
I want to get firstName and lastName in table driver_duties on the basis of driverId how can I get this. I am new to JPA I have tried #OnetoOne but not able to implement.
Add Duties as a data memeber in the class info
#Entity
#Table(name="driver_info")
public class Info{
private String driverId;
private String firstName;
private String lastName;
private Duties duties;
// with getter and setters
}
Ideally you need the following config, you should use an id attribute for every entity,
#Entity
#Table(name="driver_duties")
public class Duties{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "hubName")
private String hubName;
#Column(name = "vehicleNumber")
private String vehicleNumber;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "duty_id")
private Info info;
// with getter and setters
}
#Entity
#Table(name="driver_info")
public class Info{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private String id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#OneToOne(mappedBy = "info", cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private Duties duties;
// with getter and setters
}

Join Two Tables without foreign keys in Spring Boot with similar Ids

Here I have two tables; both have IDs as primary keys. I want to know how to join these tables without foreign keys, based on their IDs. What should be the service implementation and what should be in the repository? How to write #Query with JOINS?
#Entity
#Table(name = "procedures")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Procedure implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ProcedureId")
private int id;
#Column(name = "ProcedureName")
private String name;
#Column(name = "ProcedureCode")
private String code;
#Column(name = "ProcedureDesc")
private String desc;
// getters and setters
}
#Entity
#Table(name = "cliniciandescriptor")
public class CPTClinicianDescriptor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id")
private int id;
#Column(name = "ConceptId")
private int conceptId;
#Column(name = "CPTCode")
private String cptCode;
#Column(name = "ClinicianDescriptorId")
private int clinicianDescriptorId;
#Column(name = "ClinicianDescriptor")
private String clinicianDescriptor;
// getters and setters
}
You can use the JOIN on syntax like in SQL
For example
select p from Procedure p join CPTClinicianDescriptor c on c.id = p.id;
Read more about that topic here:
https://72.services/how-to-join-two-entities-without-mapped-relationship/
Considering it as One-to-One relation, you can use something like this.
#Entity
#Table(name = "procedures")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Procedure implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ProcedureId")
private int id;
#Column(name = "ProcedureName")
private String name;
#Column(name = "ProcedureCode")
private String code;
#OneToOne(optional = false)
#JoinColumn(name = "id", updatable = false, insertable = false)
private CPTClinicianDescriptor descriptor;
#Column(name = "ProcedureDesc")
private String desc;
// getters and setters
}

Spring JPA: How to insert data to join many tables with #ManytoMany relationship

I'm starting to learn Spring Java Framework . I created some Enity to join 2 Model like my Database. And now I want to insert to Join Table by JpaRepository. What i have to do?
This is my Code (Please fix help me me if something is not right)
Model Users_RoomId to define Composite Primary Key
#Embeddable
public class Users_RoomId implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "ID_room", nullable = false)
private String idRoom;
#Column(name = "user_id", nullable = false)
private int idUser;
}
Model Users_Room to join 2 Model Users and Room
#Entity
#Table(name ="bookroom")
public class Users_Room {
#EmbeddedId
private Users_RoomId usersroomId;
#ManyToOne
#MapsId("idRoom")
private Room room;
#ManyToOne
#MapsId("idUser")
private Users users;
#Column(name = "Bookday")
private String bookday;
Model Users and Room I used annotation #OneToMany
Model Users
#Entity
#Table(name = "users")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id", nullable = false)
private int id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "email")
private String email;
#Column(name = "pass")
private String pass;
#Column(name = "role")
private int role;
#OneToMany(mappedBy = "users")
private List<Users_Room> user;
Model Room
#Entity
#Table(name ="room")
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID_room", nullable = false)
private String id;
#Column(name = "name_room", nullable = false)
private String name;
#Column(name = "Description")
private String describe;
#ManyToOne
#JoinColumn(name = "ID_status")
private Status status;
#Column(name = "room_image")
private String image;
public Room() {
super();
}
#ManyToOne
#JoinColumn(name = "ID_kind")
private KindRoom kind;
#OneToMany(mappedBy = "room")
private List<Users_Room> rooms;
This is my database
So I don't know how to insert a new bookroom with iduser,idroom and bookday with JPA repository.. It'necessary to write Query in JPARepository or We just need to use method save() to insert data
Thanks everyone
I had same problem and solved with following code. I used method save() to insert data. Following code is 'createRoom' method in 'RoomService.java'.
RoomService.java
private final RoomRepository roomRepository;
private final UserRoomRepository userRoomRepository;
private final UserRepository userRepository;
public RoomService(RoomRepository roomRepository, UserRoomRepository userRoomRepository, UserRepository userRepository) {
this.roomRepository = roomRepository;
this.userRoomRepository = userRoomRepository;
this.userRepository = userRepository;
}
#Transactional
public RoomDto createRoom(Long userId, Long chattingUserId) {
Room room = roomRepository.save(new Room());
room.addUserRoom(userRepository.findById(userId).orElseThrow(()->new NoSuchElementException("No User")));
room.addUserRoom(userRepository.findById(chattingUserId).orElseThrow(()->new NoSuchElementException("No User")));
userRoomRepository.save(new UserRoom(userRepository.findById(userId).orElseThrow(()->new NoSuchElementException("No User")),room));
userRoomRepository.save(new UserRoom(userRepository.findById(chattingUserId).orElseThrow(()->new NoSuchElementException("No User")),room));
RoomDto roomDto = RoomDto.of(room);
return roomDto;
}

Customizing HATEOS URI

I have a Spring Boot Data Rest project I'm working on.
Specifically, I have the following dependencies:
dependencies {
compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.1.9.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-data-rest:1.1.9.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-actuator:1.1.9.RELEASE'
}
I have three entities:
#Entity
#Table(name = "prefecture", uniqueConstraints={#UniqueConstraint(columnNames = {"code", "name"})})
public class Prefecture implements Serializable {
private static final long serialVersionUID = -4664664252005282494L;
#Id
#Column(name = "code")
private Integer code;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "prefecture")
private List<City> cities;
...
#Entity
#Table(name = "city", uniqueConstraints = {#UniqueConstraint(columnNames = {"code", "name"})})
public class City implements Serializable {
private static final long serialVersionUID = 1077260811602686775L;
#Id
#Column(name = "code")
private Integer code;
#ManyToOne
#JoinColumn(name = "prefecture_code", referencedColumnName = "code")
private Prefecture prefecture;
#Column(name = "name", unique = true)
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "city")
private List<TownArea> townAreas;
...
#Entity
#Table(name = "town_area", uniqueConstraints={#UniqueConstraint(columnNames = {"name"})})
public class TownArea implements Serializable {
private static final long serialVersionUID = -4908446167092081914L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "city_code", referencedColumnName = "code")
private City city;
#Column(name = "prefecture_code")
private Integer prefectureCode;
#Column(name = "postal_code")
private String postalCode;
...
And three repositories:
#RepositoryRestResource(collectionResourceRel = "cities", path = "cities")
public interface CityRepository extends PagingAndSortingRepository<City, Integer> {}
#RepositoryRestResource(collectionResourceRel = "prefectures", path = "prefectures")
public interface PrefectureRepository extends PagingAndSortingRepository<Prefecture, Integer> {}
#RepositoryRestResource(collectionResourceRel = "town_areas", path = "town_areas")
public interface TownAreaRepository extends PagingAndSortingRepository<TownArea, Integer> {}
Given this, when I run my application locally I have a set of URLs like this:
http://localhost:8080/prefectures
http://localhost:8080/prefectures/1
http://localhost:8080/prefectures/1/cities
http://localhost:8080/cities/2/townareas
http://localhost:8080/townareas/3
However, I would like to configure the following URLs:
http://localhost:8080/prefectures/1/cities/2/
http://localhost:8080/prefectures/1/cities/2/townareas
http://localhost:8080/prefectures/1/cities/2/townareas/3
Is there a way I can customize the uris to accomplish this?

Resources