How to validate fields of own fields in JSF? - java

It sounds strange. But i need to validate the field Adress of Company in Person entity.
Company is a field of Person and Addres is afield of Company.
I want to validate the address of Company in Person entity.
Why?? Because The company should have an address if i use it in a Person entity not before?
How can I implement this validation??
#Entity
#Table(schema = Constants.DB_SCHEMA)
public class Person{
Company company;
// Validation of the address should come here ???
public Company getCompany() {
return company;
}
}
#Entity
#Table(schema = Constants.DB_SCHEMA)
public class Company{
String address;
}

Basically you can do that with the annotation #NotNull on the address attribute of your Company class.
But: Your current code won't work anyway because you have not specified the relation between the classes and you don't have primary keys....
Here is an example how it could work:
#Entity
public class Person {
#Id
#GeneratedValue
private Long id;
#OneToOne(cascade= CascadeType.ALL)
private Company company;
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
and
#Entity
public class Company {
#Id
#GeneratedValue
private Long id;
#NotNull
private String adress;
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

Related

JSON deserializer returns "null" for Collection type in REST api #RequestBody

I Have a rest controller that is not de-serializing the array type in json..
#PostMapping()
#ResponseBody
public ResponseEntity<Team> createteam(#RequestBody Team team) throws JsonProcessingException {
Team savedTeam = teamService.createTeam(team);
return new ResponseEntity<Team>(savedTeam, HttpStatus.CREATED);
}
below is my entity class.
#Entity
#JsonIdentityInfo(generator = IntSequenceGenerator.class)
public class Team {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "team", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Developer> developers;
public Team(String name, List<Developer> developer) {
super();
this.name = name;
this.developers = developer;
}
public Team() {
super();
}
public List<Developer> getDeveloper() {
return developers;
}
public void setDeveloper(List<Developer> developer) {
this.developers = developer;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and my other entity..
package com.demo.springbootdemo.entity;
#Entity
#JsonIdentityInfo(generator = IntSequenceGenerator.class)
public class Developer {
#Id
#GeneratedValue
private Long id;
#ManyToOne
private Team team;
private Long phone;
private String name;
public Developer() {
super();
}
public Developer(Team team, Long phone, String name) {
super();
this.team = team;
this.phone = phone;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
below is my JSON payload, which returns null "developers" when i call the post method.i have tried changing the number of properties in json payload but, still i am not able to figure out why my json is not de-serilaized to List of developers..
{
"id": 1004,
"name": "claim",
"developers": [
{
"id" :1,
"phone": 9092123,
"name": "raina"
}
]
}
I am not sure what Deserializer are you using, but with the Jackson ObjectMapper I solved it changing the method names of the getter and setter for the developers properties: they should be called setDevelopers and getDevelopers. In your code they are called setDeveloper and getDeveloper, without the final S.
To avoid problem like these, I just add Lombok as a dependency and it takes care of creating setters and getters.
With Lombok your Team class would look like this:
// ... more imports here...
import lombok.Data;
#Data
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public class Team {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "team", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Developer> developers;
}
You may need to add more Lombok annotations for generating constructor methods according to your needs.

Java Spring: My POST method is not inserting the id from my relationship

I'm learning Spring Framework, i followed some tutorials of relationship 1-1, so i defined my models: One Library have one Address.
I send in my body request the library data and the id from the address, the spring create the record, but he can't do the relationship, returning address null and when i make a select in database, the address_id is not saving in the table library
This is what i tried:
My model Library:
#Entity
#Table(name = "Bibliotecas")
public class Library implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
#OneToOne
#JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
public Library() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
My model Address:
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(nullable = false)
private String location;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
#OneToOne(mappedBy = "address", fetch = FetchType.LAZY, optional = false)
private Library library;
}
My repositories:
public interface LibraryRepository extends JpaRepository<Library, Long> {}
public interface AddressRepository extends JpaRepository<Address, Long> {}
My library resource:
#RestController
#RequestMapping(value = "/api")
public class LibraryResource {
#Autowired
LibraryRepository libraryRepository;
#GetMapping("/libraries")
public List<Library> listaBibliotecas() {
return libraryRepository.findAll();
}
#PostMapping("/library")
public Library salvaBiblioteca(#RequestBody Library library) {
return libraryRepository.save(library);
}
}
I do this request in Postman:
{
"name": "library test",
"address_id": 1
}
Obs: i have one address with id 1 in database, but i receive:
{
"id": 5,
"name": "Biblioteca test",
"address": null
}
Why i'm receiving null in my return? And why my register is not saving the address_id?
Please consider the following:
You switched the mapping between address & library
Better to user Hibernate annotations on public fields
Address -> Library getter & setter not implemented
Address entity missing the #table annotation
This must work for you:
Library:
#Entity
#Table(name = "library")
public class Library implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String name;
private Address address;
public Library() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToOne(mappedBy = "library", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address:
#Entity
#Table(name = "address")
public class Address {
private long id;
private String location;
private Library library;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
#Column(nullable = false)
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id")
public Library getLibrary() {
return library;
}
public void setLibrary(Library library) {
this.library = library;
}
}
Better never expose your repositories to controller, you should instead reference a service that has access to repositoryDao.
Use same entity name as table name is better approach.

Hibernate JPA No join table created on ManyToMany association

I'm trying to make a many to many association with hibernate (with JPA) but my association table (between Film and Actor) is not created.
My actor class :
#Entity
public class Actor {
private Long id;
private String firstname;
private String lastname;
private int age;
public Actor(){};
public Actor(String firstname, String lastname){
this.firstname=firstname;
this.lastname=lastname;
}
#ManyToMany
#JoinTable(name="actor_films", joinColumns=#JoinColumn(name="actor_id"), inverseJoinColumns=#JoinColumn(name="film_id"))
private Set<Film> films=new HashSet<Film>();
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void addFilm(Film film){
this.films.add(film);
}
}
My Film class :
#Entity
public class Film {
private Long id;
private String title;
#ManyToMany(mappedBy = "films")
#JoinTable(name="actor_films", joinColumns=#JoinColumn(name="film_id"), inverseJoinColumns=#JoinColumn(name="actor_id"))
private Set<Actor> actors=new HashSet<Actor>();
public Film(){};
public Film(String title){
this.title=title;
};
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void addActor(Actor actor){
this.actors.add(actor);
}
}
In my main method I do something like:
// begin transaction
Film film=new Film("DBZ");
Actor actor=new Actor("Bob","A");
em.persist(actor);
em.persist(film);
film.addActor(actor);
// do commit
All tables is created in my hsql database except the association table. So if anyone can help me.
You're mixing field and accessor use for your mapping annotations. You can't do that. In any given class, mapping annotations must be either all on the getters or all on the fields. If you try to mix them, some on the getters and some on the fields, Hibernate will pick getters or fields and ignore the other (I'm not sure if its specified how Hibernate chooses if you don't specify).
Your #Id annotation in each class is on a getter, and that's making Hibernate use your getter-based annotations. Either move the #Id and #GeneratedValue annotations to the id field in each class, or define a getter (and setter) for the actor/film relationship and move the #ManyToMany and #JoinTable annotations to the new getter.
With the annotations on the fields, Hibernate will bypass your getters/setters and access the entity internal fields directly. With them on the getters, Hibernate will call your getters and setters.
Help Hibernate a bit by providing it more information regarding your join table.
In your Film entity
#ManyToMany(mappedBy = "films")
#JoinTable(name="actor_films", joinColumns=#JoinColumn(name="film_id"), inverseJoinColumns=#JoinColumn(name="actor_id"))
Do the same in your Actor entity, but reverse joinColumns and inverseJoinColumns
https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch07.html#collections-bidirectional

How to create a many to many relationship with extra columns in jhipster?

The jhipster doesn't support create many to many relationships with extra fields.
What is the best way to create many to many association with extra columns in jhispter? Should i create a two one-to-many relationship with extra fields?
Using JHipster Domain Language (JDL), a #ManytoMany holding extra properties (columns) can be easily achieved using an association entity and two ManyToOne relationships. See below:
entity Foo{
...
}
entity Bar{
...
}
entity FooBarAssociation{
extraProperty1 String
extraProperty2 String
...
}
relationship ManyToOne {
FooBarAssociation{foo} to Foo{bars}
FooBarAssociation{bar} to Bar{foos}
}
You will have to do it manually.
this post describes how: https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/
In general, as #Antares42 said, you should create an entity for the Many-To-Many table like so:
first entity:
#Entity
public class Book{
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Book() {
}
public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
secound entity:
#Entity
public class Publisher {
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "publisher")
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
Join table entity:
#Entity
#Table(name = "book_publisher")
public class BookPublisher implements Serializable{
private Book book;
private Publisher publisher;
private Date publishedDate;
#Id
#ManyToOne
#JoinColumn(name = "book_id")
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
#Id
#ManyToOne
#JoinColumn(name = "publisher_id")
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
#Column(name = "published_date")
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}
This entity describes the relationship between Book and Publisher and the extra field is published_date
Let's say you have entities like Movie, Rater and needs a join table Ratings. You can write a JDL script like the following:
entity Movie { title String}
entity Rater { name String}
entity Rating { value Integer} //the extra field
relationship ManyToMany {
Rating{rater(name)} to Rater,
Rating{movie(title)} to Movie
}
save it in file.jdl in the project folder, open cmd type
jhipster import-jdl file.jdl
and you have everything

Exception in accessing the primary key

I have two tables in program
#Entity
#Table(name="managerlog")
public class Manager {
private Integer id;
private Address address;
#Id
#Column(name="id")
#GeneratedValue
public Integer getId() {
return id;
}
#OneToOne(mappedBy="mng")
public Address getAddress() {
return address;
}
public void setId(Integer id) {
this.id = id;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address pojo class
#Entity
#Table(name="Address")
public class Address {
private Integer id;
private String locality;
private Manager mng;
public Address()
{
}
public Address(String locality) {
this.locality = locality;
}
public Address(Integer id,String locality) {
this.id=id;
this.locality = locality;
}
#Id
#GeneratedValue
#Column(name="id")
public Integer getId() {
return id;
}
#Column(name="locality")
public String getLocality() {
return locality;
}
#OneToOne
#JoinColumn(name="MID")
public Manager getMng() {
return mng;
}
public void setLocality(String locality) {
this.locality = locality;
}
public void setId(Integer id) {
this.id = id;
}
public void setMng(Manager mng) {
this.mng = mng;
}
}
Address table in db is Manager(id,locality,mid)
Problem is i want to access address id based on mid with hibernate query like
Query qry=session.createQuery(" address.id From Address address where address.mid=:MID");
and i set the parameter .. giving me error
Exception in thread "main" java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
..
Here I know the way of getting Manager class ..from that class getting address.. but if i have MID(foreign key) ..can't I get the address.id(primary key)..
Can anyOne explain me ??
The main problem is that the Address class doesn't have the property mid, bacause mid is just the column of the your database structure. If you want to get the address for that manager, you have to change the query in this way:
Query qry=session.createQuery(" address.id From Address address where address.mid.id=:MID");
in this case you can set the manager identificator and all should works

Categories

Resources