Exception in accessing the primary key - java

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

Related

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.

How to find embedded entity?

I am playing with Spring JPA, and not able to achieve below:
#Entity
#Table(name = "User")
public class User implements Serializable {
#Column
private String name;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Address address;
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;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected long id;
private final static long serialVersionUID = 1L;
}
#Entity
#Table(name = "Location")
public class Location implements Serializable {
#Column
private String address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
protected long id;
private final static long serialVersionUID = 1L;
}
I have repositories for each domain model.
I want to get 'Address' by name such as 'findAddressByName()'. I have tried various different thing but always get User back. Can I get Address ? Is there a way to do ? Or that is how domain model specific works by default.

Hibernate - Does hibernate use proxy objects if there is no associations?

There is no association in the entity shown below.Does hibernate use proxy object to retrieve the User object?The question is little bit same as this one.But what if there is no associations?
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue
private int id;
private String name;
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;
}
}
Use this to test for proxy
boolean proxy = user instanceof HibernateProxy;

Adding foreign key field to a javabean

Consider this regular javabean without ORM/:
// primary key is auto incremented by the database, so I can't add it
public class User {
String name;
int personID; // foreign key
// no args constructor
// getter/setters for fields
}
Is it ok to do this? I personally think it doesn't make sense because there is no reason to manipulate the foreign key through the bean, but I might be wrong. Are there use cases where this is good?
I would normally do it like this.
public class Person {
private final String id;
public Person(String id) {
this.id = id;
}
public Person() {
this.id = UUID.randomUUID().toString();
}
}
and
public class User {
private final String id;
private String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User() {
this.id = UUID.randomUUID().toString();
}
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
}
Another alternative for User is to make it immutable. In which case it would look something like this.
public class User {
private final String id;
private final String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User(String personId) {
this.personId = personId;
this.id = UUID.randomUUID().toString();
}
public String getPersonId() {
return personId;
}
}
Now the classes can be used in an autoincremented or non-autoincremented way. Basically the option is there for the classes to make their own unique ID or for a unique ID to be passed to it.
One common dilemma that I have seen is when the id does not exist yet the object does. That is the case when the object is created in the program but the ID (which maybe created by the DB when it is inserted) is not assigned to it yet. In that case the bean may look like this.
public class User {
private String id;
private final String personId;
public User(String id, String personId) {
this.id = id;
this.personId = personId;
}
public User(String personId) {
this.personId = personId;
}
public String getPersonId() {
return personId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Notice the id is not final and hence the object can exist without the id present and can be added in later if needed
You are better off modelling the objects and their relationships to one another in an object oriented way.
public class User {
private long id;
private Person person;
// .... Removed for clarity
}

How to validate fields of own fields in JSF?

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;
}
}

Categories

Resources