I'm doing a registration and I have the fields
Nome:
Data de Nascimento:
Inscrição Estadual:
Nome Responsável:
CPF Responsável:
Cep:
Bloco:
Número:
when i saving, I can not write data from the PessoasEnderecos class, the other data is recording normal. I'm getting all the data on the screen so much that I debugged the browser to see ..
It shows no error. Does anyone know what I'm missing ??
my class Pacientes
#Entity
#Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable {
private static final long serialVersionUID = 5776384003601026304L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idPaciente")
private Long idPaciente;
#JoinColumn(name="idPessoa")
#ManyToOne(cascade = CascadeType.ALL)
private Pessoas pessoa;
#Column(name = "nomeResponsavel")
private String nomeResponsavel;
#Column(name = "cpfResponsavel")
private String cpfResponsavel;
public Pacientes() {
}
//gets and sets
}
my class Pessoas
#Entity
#Table(name = "pessoas", schema="glb")
public class Pessoas implements Serializable {
private static final long serialVersionUID = -4042023941980758267L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
private Long idPessoa;
#Temporal(TemporalType.DATE)
private Date dataNascimento;
private String inscricaoEstadual;
private String inscricaoMunicipal;
private String nome;
public Pessoas() {
}
//gets and sets
}
#Entity
#Table(name = "pessoas_enderecos" ,schema="glb")
public class PessoasEnderecos implements Serializable {
private static final long serialVersionUID = -2560542418318988673L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idPessoaEndereco;
private String bloco;
private String cep;
private String numero;
#JoinColumn(name="idPessoa")
#ManyToOne(optional = false, cascade = CascadeType.ALL)
private Pessoas pessoa;
public PessoasEnderecos() {
}
//gets and sets
}
my methods
class Controller
#RequestMapping(method = RequestMethod.POST, value = "/pacientes")
public Pacientes cadastrarPacientes(#RequestBody Pacientes pac) {
return pacientesService.cadastrar(pac);
}
class service
public Pacientes cadastrar(Pacientes pacientes){
return pacRepository.save(pacientes);
}
class repository
public interface PacientesRepository extends JpaRepository<Pacientes, Integer> {
}
You should also add the linkage #OneToMany in Pacientes:
public class Pacientes implements Serializable {
...
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "pessoa")
#PrimaryKeyJoinColumn
private List<PessoasEnderecos> pessoasEnderecos = new ArrayList<>();
Update:
and your JSON should be something like this:
{
"nomeResponsavel": "abc",
"pessoasEnderecos": [
{
"bloco": "sdds",
"cep": "sdasdsad",
"numero": "sdasdsa"
}
]
}
Related
Here are my entity classes.
JobPost.java
#Entity
#Table(name = "job_post")
public class JobPost {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "job_post_id")
private Long jobPostId;
#Column(name = "job_title")
private String jobTitle;
#Column(name = "job_description")
private String jobDescription;
#Column(name = "vacancy")
private int vacancy;
#Column(name = "posted_date")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date postedDate;
#Column(name = "total_applicants")
private int totalApplicants;
}
JobApplication.java
#Entity
#Table(name = "job_application")
public class JobApplication {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "job_application_id")
private Long jobApplicationId;
#Column(name = "job_post_id")
private Long jobPostId;
#Column(name = "applicant_id")
private Long applicantId;
}
Applicant.java
#Entity
#Table(name = "applicant")
public class Applicant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "applicant_id")
private Long applicantId;
#Column(name = "applicant_name")
private String applicantName;
#Column(name = "applicant_mobile_no")
private String applicantMobileNo;
#Column(name = "applicant_email")
private String applicantEmail;
}
My main goal is to listing the ApplicantList on JobPostId. I am totally new in Spring data JPA. Is JPA mappings are correct?. I don't know which query I should fire in order to fetch the applicantList based on jobPostId.
I would recommend to use JpaMappings and use SpringData instead of using native query.
Steps to follow:
Many-To-Many:
Use JoinTable to directly map JobPost and Applicant instead of creating a separate class.
Link for help:
https://attacomsian.com/blog/spring-data-jpa-many-to-many-mapping
Use SpringData JPA findOne or findById method (depends on spring version). If you use EAGER fetch then it will give you all Applicants associated with the JobPost Id.
One-To-Many
Keep JobApplication class and use OneToMany annotation.
Link for help:
https://attacomsian.com/blog/spring-data-jpa-one-to-many-mapping
Query:
#Query("select a from JobPost j inner join j.jobApplicantList ja inner join ja.applicant a where j.jobPostId=:jobPostId")
List<String> findAllJobApplicants(#Param("jobPostId") Long jobPostId);
I think that you should configure the mappings in such a way.To do this, you only need two entities
JobPost.java
#Entity
#Table(name = "job_post")
public class JobPost {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "job_title")
private String jobTitle;
#Column(name = "job_description")
private String jobDescription;
#Column(name = "vacancy")
private int vacancy;
#Column(name = "posted_date")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date postedDate;
#Column(name = "total_applicants")
private int totalApplicants;
#ManyToMany
#JoinTable(name = "applicant_job_post",
joinColumns = {
#JoinColumn(name = "job_post_id", referencedColumnName = "id")
}, inverseJoinColumns = {
#JoinColumn(name = "applicant_id", referencedColumnName = "id")
})
private Set<Applicant> applicants;
public JobPost() {
}
public void addApplicant(Applicant applicant) {
applicants.add(applicant);
applicant.getJobPosts().add(this);
}
public void removeApplicant(Applicant applicant) {
applicants.remove(applicant);
applicant.getJobPosts().remove(this);
}
}
Applicant.java
#Entity
#Table(name = "applicant")
public class Applicant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "applicant_name")
private String applicantName;
#Column(name = "applicant_mobile_no")
private String applicantMobileNo;
#Column(name = "applicant_email")
private String applicantEmail;
#ManyToMany(mappedBy = "applicants")
private Set<JobPost> jobPosts;
public Applicant() {
}
public void addJobPost(JobPost jobPost) {
jobPosts.add(jobPost);
jobPost.getApplicants().add(this);
}
public void removeJobPost(JobPost jobPost) {
jobPosts.remove(jobPost);
jobPost.getApplicants().remove(this);
}
}
I have a model class like below:
#Entity
#Table(name = "User")
public class UserModel implements Serializable{
private static final long serialVersionUID = 204096185700135310L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id", unique = true, nullable = false)
private Integer userId;
#Column(name = "user_login_name")
private String userLoginName;
#Column(name = "user_email_id")
private String userEmailId;
#Column(name = "user_password")
private String userPassword;
}
and I am writting a criteria with projection to get the userLoginName based on userId, like SELECT user_login_name from USER where user_id=1 :
public UserModel getUserByUserName(Integer userId) {
return (UserModel) HibernateService.getSession(sessionFactory)
.createCriteria(UserModel.class)
.setProjection(Projections.projectionList()
.add(Projections.property("userLoginName"), "userLoginName"))
.add(Restrictions.eq(AppConstant.USER_Id, userId))
.uniqueResult();
}
But it's throwing java.lang.String cannot be cast to com.app.aus.model.UserModel excetion. can someone help me here
i have a problem
I have two entities:
Entity ALBERO
#Entity
#IdClass(Albero.class)
#Table(schema="organo", name = "albero")
public class Albero implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "cmu")
#OneToOne
private Struttura cmu;
#Id
#JoinColumn(name = "padre")
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne
private Struttura padre;
#Column(name = "div")
private Date div;
#Column(name = "dfv")
private Date dfv;
#Column(name = "cso", length=15)
private String cso;
... get and set methods
and Entity STRUTTURA
#Entity
#Table(schema="organo", name="strutture")
#SqlResultSetMapping(
name = "Albero",
classes = #ConstructorResult(
targetClass = Albero.class,
columns = {
#ColumnResult(name="cmu", type=String.class),
#ColumnResult(name="padre", type=String.class)
}
)
)
public class Struttura implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cmu")
private String cmu;
#Column(name = "nome", length=512)
private String nome;
#Column(name = "tipologia")
private String tipologia;
#Column(name = "data_creazione")
private Date data_creazione;
...get and set methods
I have a Repository AlberoRepository with the method:
public List<Albero> findByDfvIsNull();
and other method with native query:
String QUERY = "SELECT a.* FROM ALBERO a WHERE DFV IS NULL";
#Query(nativeQuery = true, value = QUERY)
public List<Albero> findAllWithDfvIsNull();
La query on Oracle DB, give me a result with 802 record.
Each record are full; they have the values.
Instead, the methods Java, give me a List of 802 object
BUT THESE OBJECTS ARE NULL.
Why ?
Can you help me ?
Thank you very much
The problem in #IdClass annotation.
You need a special class for PK:
public class AlberPK implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "cmu")
#OneToOne
private Struttura cmu;
#Id
#JoinColumn(name = "padre", nullable = true)
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne
private Struttura padre;
}
... and change a little in Albero.class:
#Entity
#IdClass(AlberPK.class)
#Table(schema = "organo", name = "albero")
public class Albero implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Struttura cmu;
#Id
private Struttura padre;
...
}
That have to work.
I am really don't understand - why you used complex PK? Re-mind your DB structure if possible. It will help you a lot in future.
I'm getting an error saying that my entity is detached when I try to persist it. When debugging I can see that the objects I try to save have an ID. I am guessing that this might be related to my annotations in JPA but I cannot figure out what is the cause of this problem.
Class with method that causes error(the last line of doStuff() is responsible):
#RestController
#RequestMapping("/test")
public class ConcreteMyController implements MyController {
private final CategoryService categoryService;
private final OrmFactory ormFactory;
private final SongService songService;
private final CategoryForSongService categoryForSongService;
#Autowired
public ConcreteMyController(CategoryService categoryService, OrmFactory ormFactory, SongService songService, CategoryForSongService categoryForSongService) {
this.categoryService = categoryService;
this.ormFactory = ormFactory;
this.songService = songService;
this.categoryForSongService = categoryForSongService;
}
#RequestMapping(method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
#Override
public void doStuff() {
String title = "BestSongInTheWorld";
String popCategoryName = "pop";
String rockCategoryName = "rock";
String jazzCategoryName = "jazz";
Song song = this.ormFactory.createSong(title, "3:14");
this.songService.save(song);
Set<Category> categories = Sets.newHashSet(new Category(popCategoryName), new Category(rockCategoryName), new Category(jazzCategoryName));
this.categoryService.save(categories);
Song retrievedSong = songService.get(title);
Set<Category> retrievedCategories = categoryService.get(Sets.newHashSet(popCategoryName, rockCategoryName));
CategoryForSong categoryForSong = new CategoryForSong(retrievedSong.getTitle(), retrievedCategories);
this.categoryForSongService.save(categoryForSong);
}
}
Entities:
#Entity
#Table
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "name")
private String name;
#Id
#GeneratedValue
private Long id;
}
#Entity
#Table
public class Song implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "duration")
private String duration;
#Column(name = "title")
private String title;
#Id
#GeneratedValue
private Long id;
}
#Entity
#Table
public class CategoryForSong implements Serializable {
private static final long serialVersionUID = 1L;
#JoinColumn(name = "categories")
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Category> categories;
#Column(name = "songTitle")
private String songTitle;
#Id
#GeneratedValue
private Long id;
}
Getters, setters, equals etc. has been omitted. The reason that CategoryForSong contains a string with a songTitle instead of an actual Song is just me trying to isolate the problem. That did not seem to help.
My services are not very interesting, so I will add the one for Song here just to show the structure:
#Service
public class ConcreteSongService implements SongService {
#Autowired
private SongRepository songRepository;
#Transactional
#Override
public void save(Song song) {
songRepository.save(song);
}
#Transactional
#Override
public Song get(String title) {
return songRepository.getByTitle(Sets.newHashSet(title)).stream().findFirst().get();
}
}
And the repository is as simple as this:
public interface SongRepository extends CrudRepository<Song, Long> {
Set<Song> getByTitle(Set<String> titles);
}
The exception looks like this:
org.hibernate.PersistentObjectException: detached entity passed to persist: proofofconcept.springmvc.model.orm.Category
Help would be very appreciated.
I'm new to JPA and trying to do relations between two tables like this:
This is the main class object XParserLinks:
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
...
This is the object class XLinksMedia
public class XLinksMedia implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected XLinksMediaPK xLinksMediaPK;
#ManyToOne #JoinColumn(name = "link_id")
private XParserLinks xParserLink;
and XLinksMediaPK
#Embeddable
public class XLinksMediaPK implements Serializable {
#Basic(optional = false)
#Column(name = "link_id", insertable = false, updatable = false)
private int linkId;
#Basic(optional = false)
#Column(name = "image")
private String image;
Are these relations correct? Because when I want to add new XLinksMedia objects in fotos list, I get LinkId = 0, but I know that LinkId is not 0, I know that LinkId variable have a value.
Here's how I try to set fotos variable in XParseLinks class (preke: is XParseLinks object witch have his primary key LinkId):
XLinksMedia foto = new XLinksMedia();
foto.setXLinksMediaPK(new XLinksMediaPK());
foto.setxParserLink(preke);
foto.getXLinksMediaPK().setImage(e.attr("src"));
preke.getFotos().add(foto);
Even I don't know what is your expectation, When I test your coding, it is OK. I just put some of the OverLoad Constructor for easy data initialization in your classes. But, you use GenerationType.IDENTITY, that's why I set auto increate column for link_id of XParserLinks. The main of the following coding is same as yours.
Your point Here's how I try to set fotos variable in XParseLinks class (preke: is XParseLinks object witch have his primary key LinkId):. Check Test.java
XParserLinks.java
#Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
}
XLinksMediaPK.java
#Embeddable
public class XLinksMediaPK implements Serializable {
#Basic(optional = false)
#Column(name = "link_id", insertable = false, updatable = false)
private int linkId;
#Basic(optional = false)
#Column(name = "image")
private String image;
public XLinksMediaPK(){
}
public XLinksMediaPK(int linkId, String image) {
this.linkId = linkId;
this.image = image;
}
//getter and setter
}
XParserLinks.java
#Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
public void add(XLinksMedia media) {
fotos.add(media);
}
}
Test.java
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
XParserLinks xParserLink = new XParserLinks("something");
XLinksMediaPK pk1 = new XLinksMediaPK(0, "image_1");
XLinksMediaPK pk2 = new XLinksMediaPK(0, "image_2");
XLinksMediaPK pk3 = new XLinksMediaPK(0, "image_3");
xParserLink.add(new XLinksMedia(pk1, xParserLink));
xParserLink.add(new XLinksMedia(pk2, xParserLink));
xParserLink.add(new XLinksMedia(pk3, xParserLink));
em.persist(xParserLink);
System.out.println("Success...");
em.getTransaction().commit();
em.close();
}
}