Thymeleaf to access data of joined tables - java

I have three tables that have one to one relation the first table is the province entity, the district entity which has a one to relation with the province and the person's entity as each person resides in on district.
I would like to access the district information in thymleaf.
#Entity
#Table (name = "provinces")
public class Province {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int provinceId;
#Column(name="province_name",unique=true,length = 25, nullable = false)
private String provinceName;
//getters and setters
}
#Entity
#Table (name = "districts")
public class District {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(unique=true,length = 25, nullable = false)
private String districtName;
#Column(unique=true, length = 10,nullable = false)
private String abbreviation;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="province")
private Province location;
}
#Entity
public class AppUser implements UserDetails {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastName;
private String email;
#OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "location_id")
private District location;
//getters and setters
}
service controller:
#GetMapping("/all")
private String viewDistricts (Model model){
model.addAttribute("listUsers",appUserService.listUser());
return "admin/users";
}
service:
public List<AppUser> listUser(){
return appUserRepository.findAll();
}
thymeleaf:
th:text="${users.location.districtName}"
org.springframework.expression.spel.SpelEvaluationException: EL1007E:
Property or field 'districtName' cannot be found on null

best practice to handle null pointer exception as follows
th:text="${users.location!=null}?${users.location.districtName}:''"
But, the root cause of the problem is that the associated object value is null.

Related

Spring JPA how to create an object with relationship to another entity in Application

I want to create a Person with an Address, each of them are an entity. My Entities seem to work, the part where i begin to struggle is on how to create a Person using the constructor where i also have to put in the Address.
personRepository.save(new Person(new Name("Test","Test"),new Adress("Street","Number","PLZ","Town"),LocalDate.parse("2000-01-01"),"email#email.com","911");
This sadly does not work so my question is how can i create a Person object with the Address.
I'm also wondering how i would add the address if i already got the address in my Address repository, is there a way to get the address or use the adress ID?
adresseRepository.save(new Adresse("Street","Number","PLZ","Town"));
Here's the code for both of the shortend.
Person:
#Entity
#Table(name = "Person")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PersonID")
private Long personID;
#Column(name = "FullName")
#Convert(converter = NameConverter.class)
private Name fullName;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="AdresseID")
private Adresse adresse;
#Column(name = "Geburtsdatum")
private LocalDate geburtsdatum;
#Column(name = "EMail")
private String email;
#Column(name = "Telefonnummer")
private String telefonnummer;
private Person() {}
public Person(Name fullName, Adresse adresse, LocalDate geburtsdatum, String email, String telefonnummer) {
this.fullName = fullName;
this.adresse = adresse;
this.geburtsdatum = geburtsdatum;
this.email = email;
this.telefonnummer = telefonnummer;
}
}
Address:
#Entity
#Table(name = "Adresse")
public class Adresse {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "AdresseID")
private Long adresseID;
#Column(name = "Strasse")
private String strasse;
#Column(name = "Hausnummer")
private String hausnummer;
#Column(name = "PLZ")
private String plz;
#Column(name = "Ort")
private String ort;
protected Adresse() {}
public Adresse(String strasse, String hausnummer, String plz, String ort) {
this.strasse = strasse;
this.hausnummer = hausnummer;
this.plz = plz;
this.ort = ort;
}
}
Ralationships are created in hibernate like this:
#Entity
#Table(name="CART")
public class Cart {
//...
#OneToMany(mappedBy="cart")
private Set<Item> items;
// getters and setters
}
Please note that the #OneToMany annotation is used to define the property in Item class that will be used to map the mappedBy variable. That is why we have a property named “cart” in the Item class:
#Entity
#Table(name="ITEMS")
public class Item {
//...
#ManyToOne
#JoinColumn(name="cart_id", nullable=false)
private Cart cart;
public Item() {}
// getters and setters
}
Soin your case you just have to add
#Entity
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
//...
#OneToOne(mappedBy = "address")
private User user;
something lilke this to your Adress Table.
Because one Adress also have one user.
For more information visit this site

JPA one2many relation, how to keep the ids

I have 3 entity classes: User, Product and Fridge. The Fridge is something between User and Product. I mean that in the Fridge I store the ID of the Product, the id of the User and some quantity. And I need to see the IDs that are(stored) used for relation.
User Entity Class:
#Entity
#Table(name = "`user`")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#NotNull
#Column(name = "username")
private String username;
#NotNull
#Column(name = "password")
private String password;
#OneToMany(mappedBy="user")
#JsonManagedReference(value = "user-fridge")
private List<Fridge> fridge;
}
Product Entity Class :
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(name = "name")
private String name;
#Column(name = "measurementUnit")
private Enum measurementUnit;
#Column(name = "calories")
private int calories;
#OneToMany(mappedBy="product")
#JsonManagedReference(value = "ingredients-products")
private List<Ingredients> ingredients;
#OneToMany(mappedBy="product")
#JsonManagedReference(value = "fridge-product")
private List<Fridge> fridge;
}
Fridge Entity Class :
#Entity(name = "Fridge")
#Table(name = "fridge")
public class Fridge{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#ManyToOne
#JoinColumn(name="user_id")
#JsonBackReference(value = "user-fridge")
private User user;
#ManyToOne
#JoinColumn(name="product_id")
#JsonBackReference(value = "fridge-product")
private Product product;
#Column(name = "quantity")
private int quantity;
#Transient
private DateFormat dform = new SimpleDateFormat("dd/MM/yy");
#Transient
private Date intermediar = new Date();
#Column(name = "added_at")
private String added_at = dform.format(intermediar);
}
What I get is something like this :
"fridge": [
{
"id": "79baae3e-8189-4ebb-8a40-2116a77693b8",
"quantity": 25,
"added_at": "25/08/21"
}
But I need the id's of the product and user as well.
How should I structure my model to get that?

SpringBoot JPA persist child of parent with nulls columns

I have strange problem. I have entity Company, Branch and Address.
Company has list of branch and every branch has address.
Im trying to persist branch with not exist before address entity, but Address is persist with nulls columns.
#Data
#Entity
#Indexed
#Table(name = "company")
public class Company {
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
private String id;
#Field
#Column(name = "full_name", nullable = false, unique = true)
private String fullName;
#OneToMany(mappedBy = "company")
private Set<Branch> branches;
}
#Data
#Entity
#Table(name = "branch")
public class Branch {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column
private String phone;
#Column
private String email;
#OneToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
#ManyToOne
#JoinColumn(name = "company_id", referencedColumnName = "id")
private Company company;
}
#Entity
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column
private String street;
#OneToOne(mappedBy = "address")
private Company company;
#OneToOne(mappedBy = "address")
private Branch branch;
}
Service ...
public Integer addBranch(BranchDto branchDto) {
Branch branch = modelMapper.map(branchDto, Branch.class);
Company company = companyRepository.getCompanyById(branchDto.getCompanyId());
branch.setCompany(company);
return branchRepository.save(branch).getId();
}
Dto...
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class BranchDto {
private Integer id;
private String phone;
private String email;
private AddressDto address;
private String companyId;
}
And that is effect...
Debugger...
What is the problem? Can you help me ?
You are using 'mappedBy' with the same id, It only works with the first one he find.
Try to change to other id.

MappingException hibernate mapping columns

I'm struggling with following issue:
Caused by: org.hibernate.MappingException: Foreign key
(FKj4uw5b6ekvxc2djohvon7lk7:bi_person_country_countries
[person_country_id])) must have same number of columns as the
referenced primary key (bi_person_country [country_id,person_id])
I created 4 models:
#Table(name = "bi_country")
#Entity
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "bi_person_country", joinColumns = #JoinColumn(name = "country_id"), inverseJoinColumns = #JoinColumn(name = "person_id"))
private Set<Person> persons;
Gender:
#Table(name = "bi_gender")
#Entity
public class Gender {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
public Integer getId() {
return id;
}
Person:
#Table(name = "bi_person")
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "last_name")
private String lastName;
#Column(name = "additional_info")
private String additionalInfo;
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "persons")
private Set<Country> countries;
#ManyToOne
private Gender gender;
PersonCountry:
#Table(name = "bi_person_country")
#Entity
public class PersonCountry {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
private Person person;
#ManyToMany
private List<Country> countries;
You dont need the PersonCountry class here as you are using #ManyToMany in both cases being Person and Country mappings.
If you have to keep it for some reason.. the linking table should not contain #OneToMany / #ManyToMany mappings, so you would have:
#ManyToOne
private Person person;
#ManyToOne
private Country country;
Keep in mind you may need to use #JoinColumn also if the database names are different than person_id and country_id.

Making one entity to have two association with other same entity

I have two entity "user" and "vehicle".
In this user can be a owner or driver of vehicle
If user is owner he will have one to many relation with vehicle that is working fine
But if user is driver he will have one to one relation with vehicle.
I am facing the problem how make two type association between two entity at the same time.
I am posting code below that may help
UserTravelDO
#Entity
#Table(name = "usertraveldo")
public class UserTravelDO implements Serializable {
#GenericGenerator(name = "gen", strategy = "increment")
#GeneratedValue(generator = "gen")
#Id
private int userid;
private String username;
private String password;
private String hint;
private String firstname;
private String middlename;
private String lastname;
private Boolean status;
#JoinColumn(name = "addressid")
#OneToOne(cascade = CascadeType.ALL)
private AddressTravelDO address;
#JoinColumn(name = "roleid")
#ManyToOne(cascade = CascadeType.ALL)
private RoleMasterDO role;
#JsonIgnore
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<VehicleTravelDO> vehicle = new ArrayList<VehicleTravelDO>();
//#JsonIgnore
#OneToOne(mappedBy="driver",fetch = FetchType.EAGER)
private VehicleTravelDO driverofvehicle;
private java.sql.Date modificationdate = new java.sql.Date(new java.util.Date().getTime());
private java.sql.Date creationdate = new java.sql.Date(new java.util.Date().getTime());
private String createdby;
private String modifiedby;
//getters and setters are below
}
VehicleTravelDO
#Entity
#Table(name = "vehicle")
public class VehicleTravelDO implements Serializable {
#GenericGenerator(name = "gen", strategy = "increment")
#GeneratedValue(generator = "gen")
#Id
private int vehicleid;
private String vehicletype;
private String vehiclenumber;
private int totalseats;
private int availableseats;
#JsonIgnore
#JoinColumn(name = "user_id")
#ManyToOne(fetch = FetchType.EAGER)
private UserTravelDO user;
//#JsonIgnore
#OneToOne(fetch = FetchType.EAGER)
private UserTravelDO driver;
//Getters and setters are below
}
After doing this foreign key are getting generated at user and vehicle table.When i insert a vehicle with a user(driver) vehicle id is not getting inserted at the user table but at vehicle table userid(driverid) is getting
inserted.

Categories

Resources