Unable to find Entity not found exception when using one-to-many bidirectional - spring

When ever post the data using postman or run the program , facing below error:
Unable to find com.example.entity.Product with id 1; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.example.entity.Product with id 1
Below is parent class:
#Entity
public class Customer {
#Id
#GeneratedValue
private Integer cust_Id;
private String cust_name;
private String city;
#OneToMany(mappedBy = "customer")
private List<Product> products;
}
Child class:
#Entity
public class Product {
#Id
private Integer pid;
private String pname;
#ManyToOne(fetch = FetchType.LAZY)
#NotFound(action = NotFoundAction.IGNORE)
#JoinColumn(name = "fk_cust_id")
private Customer customer;
}

#NotFound(action=NotFoundAction.IGNORE) results in EAGER loading for #ManyToOne(fetch = FetchType.LAZY) field. Refer here

Related

nested exception is org.hibernate.MappingException: Could not determine type for: Com.test.model.Client, at table: ComptePaiement

I'm using Hibernate in my spring project. But It doesn't work for One-To-One relationships. It gives me the below error.
Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.example.TransfertNational.model.Client, at table: ComptePaiement, for columns: [org.hibernate.mapping.Column(client)]
I have ran some searches in the internet, but it doesn't work for me.
the Client Entity :
#Data #Entity
#AllArgsConstructor #NoArgsConstructor #ToString
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String typeTransfert;
private String typePiece;
private String cin;
private String sexe;
private String prenom;
private String typePieceIdentite;
private String paysEmission;
private String numPI;
private String validitePI;
private String dateNaissance;
private String profession;
private String nationalite;
private String paysAdresse;
private String adresseLegale;
private String ville;
private String gsm;
private String email;
#OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private Set<Beneficiaire> beneficiares;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
private ComptePaiement comptePaiement;
}
the ComptePaiement Entity :
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class ComptePaiement {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String solde;
private String rip;
private Client client;
}
Answer from comments:
You are probably missing #JoinColumn on Client or ComptePaiement and mappedBy in #OneToOne annotation, depending which will hold reference id in database.

Spring Data Projection with OneToMany error

I have a entity call Circuit.
#Entity
public class Circuit implements Comparable<Circuit>, Serializable {
#Column
private String id;
#OneToMany(mappedBy = "circuit", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Step> workflow = new HashSet<>();
...
}
I have a class called CircuitLight
public class CircuitLight {
private String id;
private Set<Step> workflow;
/* constructor, getters and setters */
}
In my CircuitRepository, i'm trying to make a projection
#Transactional(readOnly = true)
#Query("select new com.docapost.circuit.CircuitLight(c.id, c.workflow) from Circuit c where c.account.siren = :siren")
Set<CircuitLight> findAllByAccountSirenProjection(#Param("siren") String siren);
When i execute, i have a error message:
could not extract ResultSet; SQL [n/a] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'circuit0_.id' in 'on clause'
I try with other entity. Every time i have a property with a relation #OneToMany, i have the issue...
Is it possible to make a projection with class (Without use a interface) when there are a relation OneToMany ?
UPDATE:
Step.class
#Entity
public class Step implements Comparable<Step>, Serializable {
private static final List<String> INDEXABLE_PROCESSES = Arrays.asList(
ParapheurWorkflowModel.SERVER,
ParapheurWorkflowModel.SIGN,
ParapheurWorkflowModel.VISA
);
#Id
#GeneratedValue
#Expose
#SerializedName("step_id")
public long id;
#ManyToOne
public Circuit circuit;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(joinColumns = #JoinColumn(name = "step_id"), inverseJoinColumns = #JoinColumn(name = "technicalGroup_id"))
private List<TechnicalGroup> technicalGroups = new ArrayList<>();
#Column(name = "step_type", nullable = false)
#Expose
#SerializedName("subprocess_ref")
public String type;
#Column(nullable = false)
public int orderIndex;
/* contructor, getters and setters */
}
UPDATE 2:
Hum.... My bad, in my circuit class, i have a EmbeddedId
#EmbeddedId
private CircuitPK key;
#Embeddable
public static class CircuitPK implements Serializable {
public String id;
public String siren;
}
I try with this code in Step.class
#ManyToOne
#JoinColumns(value = {
#JoinColumn(name = "circuit_siren", referencedColumnName = "siren"),
#JoinColumn(name = "circuit_id", referencedColumnName = "id")
})
public Circuit circuit;
The result is the same
Write the following code in the Step entity
#ManyToOne
#JoinColumn(name="id", nullable=false)
private Circuit circuit;

How to use #NamedEntityGraph with #EmbeddedId?

I'm trying to have Spring Data JPA issue one query using joins to eagerly get a graph of entities:
#Entity
#NamedEntityGraph(name = "PositionKey.all",
attributeNodes = {#NamedAttributeNode("positionKey.account"),
#NamedAttributeNode("positionKey.product")
})
#Data
public class Position {
#EmbeddedId
private PositionKey positionKey;
}
#Embeddable
#Data
public class PositionKey implements Serializable {
#ManyToOne
#JoinColumn(name = "accountId")
private Account account;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
}
Here's my Spring Data repo:
public interface PositionRepository extends JpaRepository<Position, PositionKey> {
#EntityGraph(value = "PositionKey.all", type = EntityGraphType.LOAD)
List<Position> findByPositionKeyAccountIn(Set<Account> accounts);
}
This produces the following exception:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [positionKey.account] on this ManagedType
I want all of the accounts and products to be retrieved in one join statement with the positions. How can I do this / reference the embedded ID properties?
I would suggest refactoring the entity this way if it possible
#Entity
#NamedEntityGraph(name = "PositionKey.all",
attributeNodes = {#NamedAttributeNode("account"),
#NamedAttributeNode("product")
})
#Data
public class Position {
#EmbeddedId
private PositionKey positionKey;
#MapsId("accountId")
#ManyToOne
#JoinColumn(name = "accountId")
private Account account;
#MapsId("productId")
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
}
#Embeddable
#Data
public class PositionKey implements Serializable {
#Column(name = "accountId")
private Long accountId;
#Column(name = "productId")
private Long productId;
}
Such an EmbeddedId is much easier to use. For instance, when you are trying to get an entity by id, you do not need to create a complex key containing two entities.

Spring POST request with relationship

I have two entity types in Spring with a relationship:
#Entity
public class Domain {
public Domain() {}
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
private String name;
private String description;
private String image;
#OneToMany(cascade=CascadeType.ALL, targetEntity=Subdomain.class,fetch = FetchType.LAZY)
#JoinColumn(name="domain_id")
private Set<Subdomain> subdomain = new HashSet<>();
//Default getters and setters
}
And the type subdomain:
#Entity
public class Subdomain {
public Subdomain() {}
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
private String name;
#JsonIgnore
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "domain_id", nullable = false)
public Domain domain;
//Default getters and setters
}
This works perfect with a get request, the relation is fetched. But how does it works with post request? I would create a new subdomain with the relationship to an existing domain:
"domain_id": "2"
And this:
"domain_id": "http://localhost/subdomain/2"
But this doesn't work. What is the best way to solve this?
Could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

Need help understanding foreign keys

I have a message class with a foreign key that should be the id of the author who wrote the message. As I understand it, the foreign key in the message class should look like the class below.
Setting the foreign key as the author object as below, seems absurd because instead of a short and human readable id like "5", I get a very long string in the database that isn't human readable.
I'm missing something, right?
message class:
public class Message {
...
private Author author; // this is the foreign key
...
#ManyToOne
#JoinColumn(name = "USERNAME")
public User getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
...
Creating the message object to be saved:
Author author = ...
message.setAuthor(author);
Assuming you are simply looking for a Many-to-One unidirectional relationship
#Entity
public class Message {
...
#ManyToOne
#JoinColumn(name="USERNAME")
private Author author;
#Entity
public class Author {
#Id
#GeneratedValue
#Column(name="USERNAME")
private Long USERNAME;
You do not post the annotations from the Author class. And it is highly probable that You are missing annotations on the Author class site. Nevertheless look below:
#Entity
#Table(name = "bill")
public class BillModel {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "bill_id")
private Integer billId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fk_shop_id")
private Shop shop;
// getters and setters
}
and class Shop
#Entity
#Table(name = "shop")
public class Shop {
#Id
#GeneratedValue
#Column(name = "shop_id")
private Integer shopId;
#Column(name = "shop_name")
private String shopName;
#OneToMany(mappedBy = "shop", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<BillModel> billModels = new HashSet<BillModel>();
// getters and setters
}

Resources