I have two tables in a relationship with each other.
When I delete a line of data in the parent table.
If the data stream that is used in the table, the error message.
If not, to delete data
SQL Server Foreign Key Update and Delete Rules
No Action : Not allowed. Error message would be generated. (I want to use this exception)
Delete row in Ma_DM_NGAN_HANG throw Exception
#Entity
#Table(name = "Ma_DM_NGAN_HANG", schema = "dbo", uniqueConstraints = #UniqueConstraint(columnNames = "MANH"))
public class DmNganHang implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
// Fields
private Long id;
private String manh;
private String tennh;
private String tentat;
private String diachi;
private String dienthoai;
private String fax;
private String email;
private String taikhoan;
private String masothue;
private Integer idDonvi;
private String website;
private String filter;
private List<DmNhanVien> dmNhanViens = new ArrayList<DmNhanVien>();
private List<DmDoiTacTknganhang> dmDoiTacTknganhangs = new ArrayList<DmDoiTacTknganhang>();
// Constructors
/** default constructor */
public DmNganHang() {
}
/** minimal constructor */
public DmNganHang(Long id, String manh, String tennh, String taikhoan) {
this.id = id;
this.manh = manh;
this.tennh = tennh;
this.taikhoan = taikhoan;
}
/** full constructor */
public DmNganHang(Long id, String manh, String tennh, String tentat,
String diachi, String dienthoai, String fax, String email,
String taikhoan, String masothue, Integer idDonvi, String website,
String filter, List<DmNhanVien> dmNhanViens,
List<DmDoiTacTknganhang> dmDoiTacTknganhangs) {
this.id = id;
this.manh = manh;
this.tennh = tennh;
this.tentat = tentat;
this.diachi = diachi;
this.dienthoai = dienthoai;
this.fax = fax;
this.email = email;
this.taikhoan = taikhoan;
this.masothue = masothue;
this.idDonvi = idDonvi;
this.website = website;
this.filter = filter;
this.dmNhanViens = dmNhanViens;
this.dmDoiTacTknganhangs = dmDoiTacTknganhangs;
}
// Property accessors
#Id
#Column(name = "ID", unique = true, nullable = false, precision = 18, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
// Code ......
#JsonInclude(JsonInclude.Include.NON_EMPTY)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "dmNganHang")
public List<DmNhanVien> getDmNhanViens() {
return this.dmNhanViens;
}
public void setDmNhanViens(List<DmNhanVien> dmNhanViens) {
this.dmNhanViens = dmNhanViens;
}
#JsonInclude(JsonInclude.Include.NON_EMPTY)
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "dmNganHang")
public List<DmDoiTacTknganhang> getDmDoiTacTknganhangs() {
return this.dmDoiTacTknganhangs;
}
public void setDmDoiTacTknganhangs(
List<DmDoiTacTknganhang> dmDoiTacTknganhangs) {
this.dmDoiTacTknganhangs = dmDoiTacTknganhangs;
}
}
#Entity
#Table(name = "Ma_DM_NHAN_VIEN", schema = "dbo", uniqueConstraints = #UniqueConstraint(columnNames = {
"MANV", "IdDonvi" }))
public class DmNhanVien implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private DmNganHang dmNganHang;
private DmPhongBan dmPhongBan;
private String manv;
private String tennv;
private String diachi;
private String hkthuongtru;
private String dienthoai;
private String masothue;
private String socmt;
private Date ngaycap;
private String noicap;
private Boolean canhancutru;
private String nhom;
private String taikhoannh;
private String tinhtranghonnhan;
private Boolean gioitinh;
private Date ngaysinh;
private Integer idDonvi;
private String filter;
private List<TnChungtuthunhap> tnChungtuthunhaps = new ArrayList<TnChungtuthunhap>();
private List<TnNguoiphuthuoc> tnNguoiphuthuocs = new ArrayList<TnNguoiphuthuoc>();
private List<DmHopDong> dmHopDongs = new ArrayList<DmHopDong>();
// Constructors
/** default constructor */
public DmNhanVien() {
}
/** minimal constructor */
public DmNhanVien(Long id, DmNganHang dmNganHang, DmPhongBan dmPhongBan,
String manv, String tennv, String diachi, String taikhoannh) {
this.id = id;
this.dmNganHang = dmNganHang;
this.dmPhongBan = dmPhongBan;
this.manv = manv;
this.tennv = tennv;
this.diachi = diachi;
this.taikhoannh = taikhoannh;
}
/** full constructor */
public DmNhanVien(Long id, DmNganHang dmNganHang, DmPhongBan dmPhongBan,
String manv, String tennv, String diachi, String hkthuongtru,
String dienthoai, String masothue, String socmt, Date ngaycap,
String noicap, Boolean canhancutru, String nhom, String taikhoannh,
String tinhtranghonnhan, Boolean gioitinh, Date ngaysinh,
Integer idDonvi, String filter,
List<TnChungtuthunhap> tnChungtuthunhaps,
List<TnNguoiphuthuoc> tnNguoiphuthuocs, List<DmHopDong> dmHopDongs) {
this.id = id;
this.dmNganHang = dmNganHang;
this.dmPhongBan = dmPhongBan;
this.manv = manv;
this.tennv = tennv;
this.diachi = diachi;
this.hkthuongtru = hkthuongtru;
this.dienthoai = dienthoai;
this.masothue = masothue;
this.socmt = socmt;
this.ngaycap = ngaycap;
this.noicap = noicap;
this.canhancutru = canhancutru;
this.nhom = nhom;
this.taikhoannh = taikhoannh;
this.tinhtranghonnhan = tinhtranghonnhan;
this.gioitinh = gioitinh;
this.ngaysinh = ngaysinh;
this.idDonvi = idDonvi;
this.filter = filter;
this.tnChungtuthunhaps = tnChungtuthunhaps;
this.tnNguoiphuthuocs = tnNguoiphuthuocs;
this.dmHopDongs = dmHopDongs;
}
// Property accessors
#Id
#Column(name = "ID", unique = true, nullable = false, precision = 18, scale = 0)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_NGANHANG", nullable = false)
public DmNganHang getDmNganHang() {
return this.dmNganHang;
}
public void setDmNganHang(DmNganHang dmNganHang) {
this.dmNganHang = dmNganHang;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_PHONGBAN", nullable = false)
public DmPhongBan getDmPhongBan() {
return this.dmPhongBan;
}
// Code .....
}
Method Delete
public <T, E extends Serializable> void delete(T entity) {
entity = entityManager.merge(entity);
entityManager.remove(entity);
}
public <T, E extends Serializable> void deletefindOne(T entity) {
E id = (E) CommonUtil.invoke(entity, "getId");
JpaRepository repository = new SimpleJpaRepository(entity.getClass(),
entityManager);
repository.delete(repository.findOne(id));
}
Thanks
Related
I am not able to fetch all records from two tables using the below query
I have tried this but I am getting a result from one table only. I want a result of both the tables i.e, client_software_param_mapping and client_file_configuration having the same ClientId which is a foreign key from third pojo(client_software_configuration) to first and second pojo.
public Result showClientConfiguration() {EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query q=entityManager.
createQuery("SELECT c FROM client_software_param_mapping c JOIN fetch client_file_configuration f ON c.ClientId=f.ClientId");
List data =q.getResultList();
return ok(Json.toJson(data));
}
first pojo
#Entity
public class client_file_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String sourceFolder;
private String sourceFile;
private String processingFolder;
private String processingFile;
private String processedFolder;
private int intervalInMin;
private String readAfterDelay;
private String parserClass;
private String directoryMode;
private String fileMode;
private String actionMode;
private String type;
private String fileExpressionResolver;
#OneToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
secondpojo
#Entity
public class client_software_param_mapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String paramKey;
private String paramValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getParamKey() {
return paramKey;
}
public void setParamKey(String paramKey) {
this.paramKey = paramKey;
}
public String getParamValue() {
return paramValue;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
#ManyToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
thirdpojo
#Entity
public class client_software_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String url;
private int port;
private String endPoint;
private String isPost;
private String isPing;
private String params;
private int serialNo;
private String dateFormat;
private String token;
}
this is the right query as it is returning the object of the third pojo present at that ClientId so it is able to understand the type of ClientId.JPQL never uses table and column names. It always uses entity names and their mapped fields/properties names.so here I have taken the object of the third pojo having the ClientId field.
select c,p from client_file_configuration c,client_software_param_mapping p where c.clientSoftwareConfiguration = p.clientSoftwareConfiguration
So first a bit of back story. The issue I am having is when I create a user. Previously I had tried to create a user and assign them a role separately before discovering that by inserting into the SEC_USER_ROLE table the program was also inserting into the APP_USER table and I was getting an error about inserting duplicate values into the parent table. However, now by creating the user and role together I am getting the following error:
Primary key should be primitive (or list of primitives for composite
pk) , an instance of java.lang.Long with the primary keys filled in or
an instance of WebIntSecRole.......
Code as follows, not sure where I'm goin g wrong or the best solution at this point.
Admin.java:
//New User Creation
WebIntUser newUser = new WebIntUser();
newUser.setLoginId(newLoginName);
newUser.setCreatedBy(loggedUser);
newUser.setCreatedOn(today);
newUser.setDbAuth(true);
newUser.setDeleted(false);
newUser.setDisabled(false);
newUser.setEmail(newEmail);
newUser.setEncrypted(true);
newUser.setEncryptPassword(true);
newUser.setFirstName(newFirstName);
newUser.setLastName(newLastName);
newUser.setUpdatedBy(loggedUser);
newUser.setUpdatedOn(today);
newUser.setVersion(1);
newUser.setLdapId(1);
//userService.createUser(newUser);
//Set role for new user
WebIntSecRoleUser newUserRole = new WebIntSecRoleUser();
newUserRole.setUser(newUser);
newUserRole.setDeleted(false);
newUserRole.setRole(userService.selectRoleById(1));
//newUserRole.setCreatedBy(loggedUser);
//newUserRole.setCreatedOn(today);
//newUserRole.setUpdatedBy(loggedUser);
//newUserRole.setUpdatedOn(today);
newUserRole.setVersionNumber(0);
userService.createRole(newUserRole);
WebIntUser.java
#Entity
#Table(name = "APP_USER")
#EntityListeners(value = { AuditChangeListener.class })
public class WebIntUser implements Serializable {
public WebIntUser() {
};
public WebIntUser(String login, String pass) {
this.loginId = login;
this.password = pass;
}
private Integer userId;
private String loginId;
private String password;
private String firstName;
private String lastName;
private String email;
private boolean disabled;
private boolean deleted;
private boolean dbAuth;
private boolean isEncrypted;
private boolean encryptPassword;
private Date lastLogin;
private Date prevLogin;
private Integer version;
private Date lastPasswordChange;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
private Integer ldapId;
public static interface propertyName {
String userId = "userId";
String loginId = "loginId";
String password = "password";
String firstName = "firstName";
String lastName = "lastName";
String email = "email";
String disabled = "disabled";
String deleted = "deleted";
String dbAuth = "dbAuth";
String isEncrypted = "isEncrypted";
String encryptPassword = "encryptPassword";
String lastLogin = "lastLogin";
String prevLogin = "prevLogin";
String version = "version";
String lastPasswordChange = "lastPasswordChange";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
String ldapId = "ldapId";
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
.....getters/setters
}
WebIntSecRoleUser.java:
#Entity
#Table(name = "SEC_ROLE_USER")
#EntityListeners(value = {AuditInfoChangeListener.class})
public class WebIntSecRoleUser implements AuditableDomainObject {
private Long id;
private WebIntSecRole role;
private WebIntUser user;
private boolean deleted;
private AuditInfo auditInfo;
private long versionNumber;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
public interface propertyName extends Auditable.propertyName {
String id="id";
String role="role";
String user="user";
String deleted = "deleted";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
}
public static interface permissionKey{
String UPDATE="SecRoleUser.U";
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ROLE_USER_ID",nullable = false, unique = true)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
}
public void setRole(WebIntSecRole role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="USER_ID", nullable = false)
public WebIntUser getUser() {
return user;
}
public void setUser(WebIntUser user) {
this.user = user;
}
Getters/setters
}
Note: There is some commented out code that I'm either trying not to use anymore, or in the case of Created By and Created On etc I was getting errors for multiple inserts.
In my opinion you have missed the #ManyToOne mapping on the WebIntSecRole. You only specified the #JoinColumn.
#ManyToOne(/* desired options */)
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
I have this bean that is auto-generated from DB:
#Entity
#Table(name = "richiesta", catalog = "gestione_utenza")
public class Richiesta implements java.io.Serializable {
private Integer idRichiesta;
private MessaggiErrore messaggiErrore;
private Stato stato;
private Date dataInserimento;
private Date dataElaborazione;
private String nota;
private String usernameAssegnato;
private String utenteAutorizzante;
private String urlattivazione;
private Anagrafica anagrafica;
private Set<RichiestaApplicazione> richiestaApplicaziones = new HashSet<RichiestaApplicazione>(
0);
public Richiesta() {
}
public Richiesta(Stato stato, Date dataInserimento) {
this.stato = stato;
this.dataInserimento = dataInserimento;
}
public Richiesta(MessaggiErrore messaggiErrore, Stato stato,
Date dataInserimento, Date dataElaborazione, String nota,
String usernameAssegnato, String utenteAutorizzante,
String urlattivazione, Anagrafica anagrafica,
Set<RichiestaApplicazione> richiestaApplicaziones) {
this.messaggiErrore = messaggiErrore;
this.stato = stato;
this.dataInserimento = dataInserimento;
this.dataElaborazione = dataElaborazione;
this.nota = nota;
this.usernameAssegnato = usernameAssegnato;
this.utenteAutorizzante = utenteAutorizzante;
this.urlattivazione = urlattivazione;
this.anagrafica = anagrafica;
this.richiestaApplicaziones = richiestaApplicaziones;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idRichiesta", unique = true, nullable = false)
public Integer getIdRichiesta() {
return this.idRichiesta;
}
public void setIdRichiesta(Integer idRichiesta) {
this.idRichiesta = idRichiesta;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "codiceErrore")
public MessaggiErrore getMessaggiErrore() {
return this.messaggiErrore;
}
public void setMessaggiErrore(MessaggiErrore messaggiErrore) {
this.messaggiErrore = messaggiErrore;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stato", nullable = false)
public Stato getStato() {
return this.stato;
}
public void setStato(Stato stato) {
this.stato = stato;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "dataInserimento", nullable = false, length = 19)
public Date getDataInserimento() {
return this.dataInserimento;
}
public void setDataInserimento(Date dataInserimento) {
this.dataInserimento = dataInserimento;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "dataElaborazione", length = 19)
public Date getDataElaborazione() {
return this.dataElaborazione;
}
public void setDataElaborazione(Date dataElaborazione) {
this.dataElaborazione = dataElaborazione;
}
#Column(name = "nota", length = 256)
public String getNota() {
return this.nota;
}
public void setNota(String nota) {
this.nota = nota;
}
#Column(name = "usernameAssegnato", length = 20)
public String getUsernameAssegnato() {
return this.usernameAssegnato;
}
public void setUsernameAssegnato(String usernameAssegnato) {
this.usernameAssegnato = usernameAssegnato;
}
#Column(name = "utenteAutorizzante", length = 20)
public String getUtenteAutorizzante() {
return this.utenteAutorizzante;
}
public void setUtenteAutorizzante(String utenteAutorizzante) {
this.utenteAutorizzante = utenteAutorizzante;
}
#Column(name = "URLattivazione", length = 80)
public String getUrlattivazione() {
return this.urlattivazione;
}
public void setUrlattivazione(String urlattivazione) {
this.urlattivazione = urlattivazione;
}
#OneToOne(fetch = FetchType.LAZY, mappedBy = "richiesta")
public Anagrafica getAnagrafica() {
return this.anagrafica;
}
public void setAnagrafica(Anagrafica anagrafica) {
this.anagrafica = anagrafica;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "richiesta")
public Set<RichiestaApplicazione> getRichiestaApplicaziones() {
return this.richiestaApplicaziones;
}
public void setRichiestaApplicaziones(
Set<RichiestaApplicazione> richiestaApplicaziones) {
this.richiestaApplicaziones = richiestaApplicaziones;
}
}
I want to add a new Richiesta, with his childs, but with the code that I wrote I'm able to add only a new row in the table Richiesta:
Richiesta ric = new Richiesta();
Stato st = new Stato();
st.setIdStato(1);
ric.setStato(st);
ric.setDataInserimento(new Date());
Integer[] appId = getApplicazioniSelezionateDefault();
for (int k=0; k<appId.length; k++)
{
Applicazione ap = new Applicazione();
ap.setIdApplicazione(appId[k]);
ric.getRichiestaApplicaziones().add( new RichiestaApplicazione( ap, ric));
}
Ufficio uf = new Ufficio();
uf.setIdufficio(this.getUfficioVDR());
Qualifica qu = new Qualifica();
qu.setIdQualifica( CommonUtil.getIndexInteger(getQualificaSelezionataVDR()) );
ric.setAnagrafica(new Anagrafica(uf, qu, ric, getCognomeVDR(), getNomeVDR(), getDataNascitaVDR(), getTelefonoVDR(), getEmailVDR(), getIpVDR()));
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(ric);
session.getTransaction().commit();
I would like to have a new row in the table Anagrafica, and "N" news rows in the table RichiestaApplicazione.
#Entity
#Table(name = "anagrafica", catalog = "gestione_utenza")
public class Anagrafica implements java.io.Serializable {
private Integer idRichiesta;
private Ufficio ufficio;
private Qualifica qualifica;
private Richiesta richiesta;
private String cognome;
private String nome;
private Date dataNascita;
private String telefono;
private String email;
private String ip;
[...]
#GenericGenerator(name = "generator", strategy = "foreign", parameters = #Parameter(name = "property", value = "richiesta"))
#Id
#GeneratedValue(generator = "generator")
#Column(name = "idRichiesta", unique = true, nullable = false)
public Integer getIdRichiesta() {
return this.idRichiesta;
}
[...]
}
I read to add the CASCADE attribute to the xml/annotation, is it possible to make it without editing annotation/xml? For example adding something in the code.
To become persistent, a new entity instance must be added to the persistent context with session.persist(newEntity) or session.save(newEntity). You haven't called this method on anything except ric. So all the other created entities are still not persistent.
I use Hibernate and
have two entities(City and Region) with OneToMany relation.
the First:
#Entity
#Table(name = "p_region")
public class Region implements Serializable{
#OneToMany(mappedBy = "region",fetch= FetchType.LAZY, cascade = CascadeType.MERGE)
private List<City> citys;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
//++++++++++++++++++++ GETSET
public List<City> getCitys() {
return citys;
}
public void setCitys(List<City> citys) {
this.citys = citys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and the second one:
#Entity
#Table(name = "p_city")
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty(message = "Название не должно быть пустым")
#Length(max = 10, min = 2, message = "Название должно быть менее 2 символов и не
более 100")
private String cityName;
#NotEmpty(message = "Код города не должно быть пустым")
private String cityCode;
#Column(name = "zone")
private Integer zone;
#Basic(optional = true)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date entryDate = Calendar.getInstance().getTime();
#ManyToOne()
private Region region;
#Basic(optional = true)
private String zip_code;
// GET SET ::::::::::::::::::::::::::::::::::
public Integer getZone() {
return zone;
}
public void setZone(Integer zone) {
this.zone = zone;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public void delete() {
System.out.println("QQQQQQQQQQQQQQQQQQQQQQ");
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
this.entryDate = entryDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getZip_code() {
return zip_code;
}
public void setZip_code(String zip_code) {
this.zip_code = zip_code;
}
}
When I try to get simple Object(City) with JSON it returns the cycle:
{"id":577,"region":{"name":"нет региона","id":15,"citys":[{"id":577,"region":
{"name":"нет региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет
региона","id":15,"citys":[{"id":577,"region":{"name":"нет......so on.
Are there any solutions for this issue?
You need to break the bi-directional relationship between your entity before converting to JSON.
I think there are two options:
Iterate the child collection, e.g. citys in Region and set Region to null. This way, circular dependency would be broken. You my want to add one name mapped attribute regionId in the City so that relational info is still available.
Create another set of POJO objects without circular dependency, copy the values from Entity Objects and then get the JSON using POJO objects.
I have a table Post and Post_Image
#Entity
#Table(name = "post")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Post.findAll", query = "SELECT p FROM Post p"),
#NamedQuery(name = "Post.findByPostId", query = "SELECT p FROM Post p WHERE p.postId = :postId"),
#NamedQuery(name = "Post.findByTitle", query = "SELECT p FROM Post p WHERE p.title = :title"),
#NamedQuery(name = "Post.findByCreatedDatetime", query = "SELECT p FROM Post p WHERE p.createdDatetime = :createdDatetime")})
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "post_id")
private Integer postId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "content")
private String content;
#Column(name = "created_datetime")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDatetime;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private User userId;
#JoinColumn(name = "post_type_id", referencedColumnName = "post_type_id")
#ManyToOne(optional = false)
private PostType postTypeId;
public Post() {
Date date = new Date();
this.createdDatetime =new Date(date.getTime());
}
public Post(Integer postId) {
this.postId = postId;
}
public Post(Integer postId, String title, String content) {
this.postId = postId;
this.title = title;
this.content = content;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDatetime() {
return createdDatetime;
}
public void setCreatedDatetime(Date createdDatetime) {
this.createdDatetime = createdDatetime;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public PostType getPostTypeId() {
return postTypeId;
}
public void setPostTypeId(PostType postTypeId) {
this.postTypeId = postTypeId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postId != null ? postId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Post)) {
return false;
}
Post other = (Post) object;
if ((this.postId == null && other.postId != null) || (this.postId != null && !this.postId.equals(other.postId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Post[ postId=" + postId + " ]";
}
}
and
#Entity
#Table(name = "post_image")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PostImage.findAll", query = "SELECT p FROM PostImage p"),
#NamedQuery(name = "PostImage.findByPostImageId", query = "SELECT p FROM PostImage p WHERE p.postImageId = :postImageId"),
#NamedQuery(name = "PostImage.findByPath", query = "SELECT p FROM PostImage p WHERE p.path = :path"),
#NamedQuery(name = "PostImage.findByTitle", query = "SELECT p FROM PostImage p WHERE p.title = :title")})
public class PostImage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "post_image_id")
private Integer postImageId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "path")
private String path;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#JoinColumn(name = "post_id", referencedColumnName = "post_id")
#ManyToOne(optional = false)
private Post postId;
public PostImage() {
}
public PostImage(Integer postImageId) {
this.postImageId = postImageId;
}
public PostImage(Integer postImageId, String path, String title) {
this.postImageId = postImageId;
this.path = path;
this.title = title;
}
public Integer getPostImageId() {
return postImageId;
}
public void setPostImageId(Integer postImageId) {
this.postImageId = postImageId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post getPostId() {
return postId;
}
public void setPostId(Post postId) {
this.postId = postId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postImageId != null ? postImageId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PostImage)) {
return false;
}
PostImage other = (PostImage) object;
if ((this.postImageId == null && other.postImageId != null) || (this.postImageId != null && !this.postImageId.equals(other.postImageId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.PostImage[ postImageId=" + postImageId + " ]";
}
}
i want to get collection of images for particular post like
Collection objPostImage = objPost.getPostImageCollection()
but manytoone relationship do not provide this functionality to me how can i convert it to one to many or how can i get Image Collection for a post.?
I am new to java so any help and suggestion will be appreciated
thanx in advance...
You can add a java.util.Set of PostImages in your Post object, and use the Hibernate mapping to provide the relationship. This site has a great example of setting up One to Many relationships.
So, for example, you would want to add something like the following to your Post class:
private Set<PostImage> postImages = new HashSet<PostImage>();
#OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
public Set<PostImage> getPostImages() {
return this.postImages;
}
public void setPostImages(Set<PostImage> postImages) {
this.postImages= postImages;
}
Then, in your PostImage class, add a reference to a Post object:
private Post post;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "POST_ID", nullable = false)
public Stock getPost() {
return this.post;
}
public void setPost(Post post) {
this.post= post;
}
After adding that, you will be able to call the getPostImages() method on your Post object.
Try this:
#Entity
#Table(name = "post")
public class Post
{
//....
#OneToMany(mappedBy = "post")
private Set<PostImage> images;
//....
}
#Entity
#Table(name = "post_image")
public class PostImage
{
//....
#JoinColumn(name = "post_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Post post;
//....
}
The reason why Seth's answer didn't work is because EclipseLink uses fields to access persistence data. (Hibernate uses properties IIRC.) You can specify per class how a JPA provider should access this data.
Using fields:
#Entity
#Access(AccessType.FIELD)
public class SomeEntity
{
#Id
private Long id;
//....
}
Using properties:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
//....
#Id
public Long getId()
{
return id;
}
}
However when using #Access(AccessType.PROPERTY) fields are also used (at least in EclipseLink) so something like this is possible:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
#Column(name = "text")
private String someText;
//....
#Id
public Long getId()
{
return id;
}
}