Hi could anyone please explain me about how to delete the parent with deleting the child's.For example When I have an entity called Class and Student.Here the parent is class and child is student.I want to delete the parent(Class) with out deleting Child as student.In Hibernate.
ClassEntity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* #author hyva
*/
#Entity
public class Calss implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#OneToMany
#Cascade(CascadeType.ALL)
#JoinColumn(name = "CalssId")
private Set<Student> student = new HashSet();
public boolean addstudent(Student s){
return student.add(s);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Calss)) {
return false;
}
Calss other = (Calss) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.myapp.struts.Calss[ id=" + id + " ]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudent() {
return student;
}
public void setStudent(Set<Student> student) {
this.student = student;
}
}
Student
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author hyva
*/
#Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentname;
private String age;
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Student)) {
return false;
}
Student other = (Student) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.myapp.struts.Student[ id=" + id + " ]";
}
}
An object has different types of associations. For example composite association in which their will be a parent object and which will control one or many child/dependent objects. The dependent objects does not have their own life cycle and identity and It cannot exist alone without parent object.
Whatever modifications such as create,update,delete happens to the parent object and it suppose to be taken place to the child objects as well . For example if I’m deleting a parent object , the deletion should not happen to the parent object alone but it should delete all this child object as well since those child object life cycle is entirely depends on the parent object . Their is a strategy called cascade in JPA and in Hibernate to enforce this methodology.
Coming back to your question. I assume Employee is your parent and phone is its child class. It does not make any point to leave the phone/child objects undeleted . Which is actually breaks the association methodology between objects.
Still you can achieve the task by executing either HQL or native SQL quires but its not recommended to so .
Hope this is helpful!
Related
There are lots of questions about this in StackOverflow. But l still can't solve it.
I am coding a tax system using Hibernate as my persistence layer.
Now, l have two entity classes:
Role.java and RolePrivilege.java.
this is Role.java
package com.taxsys.nsfw.role.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name="role")
public class Role implements Serializable{
#Id
#GenericGenerator(name="pk_hilo", strategy="hilo")
#GeneratedValue(generator="pk_hilo")
#Column(name="role_id")
private String roleId;
#Column(name="role_name",length=32, nullable=false)
private String roleName;
#Column(name="state", length=1)
private String state;
#OneToMany(targetEntity=RolePrivilege.class,
mappedBy="role", cascade=CascadeType.ALL,
fetch=FetchType.EAGER)
private Set<RolePrivilege> role = new HashSet<>();
public static String ROLE_STATE_VALID = "1";
public static String ROLE_STATE_INVALID = "0";
public Set<RolePrivilege> getRolePrivilege() {
return role;
}
public void setRolePrivilege(Set<RolePrivilege> rolePrivilege) {
this.role = rolePrivilege;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Role() {
}
public Role(String roleId, String roleName, String state, Set<RolePrivilege> rolePrivilege) {
super();
this.roleId = roleId;
this.roleName = roleName;
this.state = state;
this.role = rolePrivilege;
}
}
this is RolePrivilege.java:
package com.taxsys.nsfw.role.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="role_privilege")
public class RolePrivilege implements Serializable{
#ManyToOne(targetEntity=Role.class, fetch=FetchType.EAGER)
#JoinColumn(name="role_id", referencedColumnName="role_id")
#Id
private Role role;
#Id
private String code;
public RolePrivilege(Role role, String code) {
super();
this.role = role;
this.code = code;
}
public RolePrivilege() {
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RolePrivilege other = (RolePrivilege) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (role == null) {
if (other.role != null)
return false;
} else if (!role.equals(other.role))
return false;
return true;
}
}
I am using Hibernate3.6,spring3.0,struts2.3 and tomcat7.
But when l start Tomcat, the error message will be showing:
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.taxsys.nsfw.role.entity.RolePrivilege.role in com.taxsys.nsfw.role.entity.Role.role
Look my code! mappedBy="role".It's the same with RolePrivilege.role!And even if l use lower-case, it doesn't work! I don't know why. Maybe it is a question about jar or compatibility? Thank you!
Remove #Id in RolePrivilege.java for private Role role; and report back what error are u still getting
You can map the composite key using #Embeddable annotation in a new class object, then use #ManyToOne mapping to map the child object to the parent object. See Hibernate annotations to map one to one unidirectional association with composite primary key
I am getting following error:
SEVERE: null
javax.jms.MessageFormatException: [C4017]: Invalid message format.
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.checkValidObjectType(MapMessageImpl.java:653)
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.setObject(MapMessageImpl.java:632)
at buyer.Main.sendCart(Main.java:287)
after I try to send Persistence object through MapMessage in JMS system. And I am not quite sure why it happens since MapMessage accepts only serializable objects for value, and Persistence entities are serializable. I would appreciate any help! My Java code is following.
package entities;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#Entity
#Table(name = "carts")
#NamedQuery(
name = "carts.findAll",
query = "select c from Cart c"
)
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "buyer_id")
private Long buyerId;
#Column(name = "card_id")
private Long cardId;
#Column(name = "successful")
private boolean successful;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "buyer_id")
private Buyer buyer;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "card_id")
private Card card;
#OneToMany(mappedBy = "cart", cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
private List<CartItem> cartItems;
public Cart() {
}
public Cart(Long buyerId, Long cardId, boolean successful) {
this.buyerId = buyerId;
this.cardId = cardId;
this.successful = successful;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBuyerId() {
return buyerId;
}
public void setBuyerId(Long buyerId) {
this.buyerId = buyerId;
}
public Long getCardId() {
return cardId;
}
public void setCardId(Long cardId) {
this.cardId = cardId;
}
public boolean isSuccessful() {
return successful;
}
public void setSuccessful(boolean successful) {
this.successful = successful;
}
public Buyer getBuyer() {
return buyer;
}
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
#Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.buyerId);
hash = 53 * hash + Objects.hashCode(this.cardId);
hash = 53 * hash + (this.successful ? 1 : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cart other = (Cart) obj;
if (this.successful != other.successful) {
return false;
}
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.buyerId, other.buyerId)) {
return false;
}
if (!Objects.equals(this.cardId, other.cardId)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Cart{" + "id=" + id + ", buyerId=" + buyerId + ", cardId=" + cardId + ", successful=" + successful + '}';
}
}
Relevant method that sends message.
private static Buyer sendCart(Cart cart, String tempId, Buyer buyer) {
JMSContext context = connectionFactory.createContext(2);
try {
Destination queue = context.createQueue("mediator");
JMSProducer producer = context.createProducer();
MapMessage message = context.createMapMessage();
message.setObject("data", cart);
message.setObject("tempid", tempId);
message.setObject("type", MessageType.BUYER_SENDING_CART);
producer.send(queue, message);
} catch (JMSException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
The Problem is the MapMessage. According to JavaDoc:
A MapMessage object is used to send a set of name-value pairs. The
names are String objects, and the values are primitive data types in
the Java programming language. The names must have a value that is not
null, and not an empty string. The entries can be accessed
sequentially or randomly by name. The order of the entries is
undefined. MapMessage inherits from the Message interface and adds a
message body that contains a Map.
And:
They may also be read or written generically as objects.
So even if MapMessage offers an "setObject" Method, the parameter used must be a primitive Type.
To pass non-primitive Types use ObjectMessage
I have 2 different tables: subjects and questions and I need to make SQL JOIN on these 2 tables. Table subjects has its attributes: name and shortcut. Table questions has its attributes: question_number, text, subject - in fact, subject from table questions is a shortcut of a subject.
I tried something like this, what I saw in one stackoverflow topic:
Query q = em.createNativeQuery("SELECT q.question_number, q.text, s.name, s.shortcut FROM "
+ "( questions q INNER JOIN subjects s ON q.subject=s.shortcut );", QuestionSubject.class);
QuestionSubject.class is an #Entity class and has attributes of both questions table and subjects table. After calling this method I saw that a new table with a name QUESTIONSUBJECT was created in my database and that is what I do not want to be done.
Can anyone help me with other solution?
P.S.: I am doing this in order to use the ouput as a response on HTTP request so I need to gather those two into one. I need to return either a List or JSON string.
EDIT: Using MySQL database.
questions table Entity class:
package model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "questions")
#XmlRootElement
public class Question implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "question_number")
private Integer questionNumber;
#Column(name = "text")
private String text;
#Column(name = "subject")
private String subject;
public Question() {
}
public Question(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public Question( String text, String subject) {
this.text = text;
this.subject = subject;
}
public Question(Integer questionNumber, String text, String subject) {
this.questionNumber = questionNumber;
this.text = text;
this.subject = subject;
}
public Integer getQuestionNumber() {
return questionNumber;
}
public void setQuestionNumber(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
#Override
public int hashCode() {
int hash = 0;
hash += (questionNumber != null ? questionNumber.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 Question)) {
return false;
}
Question other = (Question) object;
if ((this.questionNumber == null && other.questionNumber != null) || (this.questionNumber != null && !this.questionNumber.equals(other.questionNumber))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Rest.Questions[ questionNumber=" + questionNumber + " ]";
}
}
subjects table Entity class.
package model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "subjects")
#XmlRootElement
public class Subject implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 5)
#Column(name = "shortcut")
private String shortcut;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "name")
private String name;
public Subject() {
}
public Subject(String shortcut) {
this.shortcut = shortcut;
}
public Subject(String shortcut, String name) {
this.shortcut = shortcut;
this.name = name;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
int hash = 0;
hash += (shortcut != null ? shortcut.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 Subject)) {
return false;
}
Subject other = (Subject) object;
if ((this.shortcut == null && other.shortcut != null) || (this.shortcut != null && !this.shortcut.equals(other.shortcut))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Rest.Subjects[ shortcut=" + shortcut + " ]";
}
}
QuestionSubject Entity class:
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class QuestionSubject implements Serializable
{
#Id
#Column(name = "question_number")
private Integer questionNumber;
#Column(name = "text")
private String text;
#Column(name = "shortcut")
private String shortcut;
#Column(name = "name")
private String name;
public Integer getQuestionNumber() {
return questionNumber;
}
public void setQuestionNumber(Integer questionNumber) {
this.questionNumber = questionNumber;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getShortcut() {
return shortcut;
}
public void setShortcut(String shortcut) {
this.shortcut = shortcut;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The table gets created because you define a class named QuestionSubject annotated as #Entity. Per default the table name is the class name.
You could override the name like you did in Subjects with #Table(name = "subjects")
Nearly the same would happen if you would define a #ManyToMany mapping on related fields between classes Question and Subject without defining QuestionSubject class at all.
I would recommend to take a look here to get more information:
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Relationship_Mappings/Collection_Mappings/ManyToMany
Edit
If you need a manyToMany mapping you need this table. Otherwise you can only have an oneToMany resp. manyToOne relation (using foreign keys).
I'm trying to map a bidirectional ManyToMany relationship between the class Problem and the class Domain. Therefore the persistency unit creates a join table in the database, but it seems no entry pops up in the database.
Here's some code:
The class Problem
package domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement
public class Problem implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private User user;
private String description;
private int maxprice;
private int priority;
private Solution solution;
private Location location;
private List<Domain> domains;
#Id
//#GeneratedValue(strategy = GenerationType.AUTO)
#SequenceGenerator(name="User_Seq", allocationSize=25)
#GeneratedValue(strategy=SEQUENCE, generator="Problem_Seq")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne
//#JoinColumn(name="user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxPrice() {
return maxprice;
}
public void setMaxPrice(int maxprice) {
this.maxprice = maxprice;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="solution_id")
public Solution getSolution() {
return solution;
}
public void setSolution(Solution solution) {
this.solution = solution;
}
#ManyToOne
#JoinColumn(name="location_id")
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
#ManyToMany
#JoinTable(name="problem_domain",
joinColumns={#JoinColumn(name="problem_id", referencedColumnName="ID")},
inverseJoinColumns={#JoinColumn(name="domain_id", referencedColumnName="ID")})
public List<Domain> getDomains() {
return domains;
}
public void setDomains(List<Domain> domains) {
this.domains = domains;
}
public void addDomain(Domain domain){
//this.domains.add(domain); //Throws NullpointerException om een of andere reden.
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Problem)) {
return false;
}
Problem other = (Problem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Problem[ id=" + id + " ]";
}
}
The class Domain
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import static javax.persistence.GenerationType.SEQUENCE;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement
public class Domain implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private List<Problem> problems;
private List<Domain> subDomains;
private Domain superDomain;
#Id
#SequenceGenerator(name="Dom_Seq", allocationSize=25)
#GeneratedValue(strategy=SEQUENCE, generator="Dom_Seq")
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;
}
#ManyToMany(mappedBy = "domains")
public List<Problem> getProblems() {
return problems;
}
public void setProblems(List<Problem> problems) {
this.problems = problems;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="superdomain_id")
public List<Domain> getSubDomains() {
return subDomains;
}
public void setSubDomains(List<Domain> subDomains) {
this.subDomains = subDomains;
}
public Domain getSuperDomain() {
return superDomain;
}
public void setSuperDomain(Domain superDomain) {
this.superDomain = superDomain;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Domain)) {
return false;
}
Domain other = (Domain) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Domain[ id=" + id + " ]";
}
}
the code where we add a problem and a domain to the database
Problem problem = new Problem();
Domain domain = new Domain();
domain.setName(domainString);
domainFacade.create(domain);
problemFacade.create(problem);
problem.addDomain(domain);
problemFacade.edit(problem);
and a little visual explanation of the DB
Do you try to save List of domain to problem?
Example of code:
Problem problem = new Problem();
Domain domain = new Domain();
domain.setName(domainString);
domainFacade.create(domain);
List<Domain> domains = new ArrayList<Domain>();
domains.add(domain);
problem.setDomains(domains);
problemFacade.create(problem);
As #Neil Stockton and others said, the answer to my problem was that I had to have an addMethod that simply added the object to the list.
I can't get working the Jersey RESTful webservices, autogenerated with Netbeans.
When POSTing the JSON like this,
{"name":"Some New Site"}
the POST query returns me this,
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert
explicit value for identity column in table 'site' when IDENTITY_INSERT is set to OFF.
Error Code: 544
Call: INSERT INTO site (id, name) VALUES (?, ?)
bind => [2 parameters bound]
Unlike MySQL, MSSQL doesn't generate new autoincremented ID when the NULL value is passed in INSERT query; it needs the ID field not to mentioned at all to generate value for it.
(IDENTITY_INSERT will not make ID to be generated either)
How do I teach my Jersey services to omit the id field in INSERT query?
edit: here's the POJO, it was generated automatically for me by Netbeans with it's "Restful Web Services From Database" wizard. (I am trying to be as little original as possible)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.fedd.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author fkravchenko
*/
#Entity
#Table(name = "site")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Site.findAll", query = "SELECT s FROM Site s"),
#NamedQuery(name = "Site.findById", query = "SELECT s FROM Site s WHERE s.id = :id"),
#NamedQuery(name = "Site.findByName", query = "SELECT s FROM Site s WHERE s.name = :name")})
public class Site implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "id")
private Long id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "siteId")
private Collection<Document> documentCollection;
public Site() {
}
public Site(Long id) {
this.id = id;
}
public Site(Long id, String name) {
this.id = id;
this.name = name;
}
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;
}
#XmlTransient
public Collection<Document> getDocumentCollection() {
return documentCollection;
}
public void setDocumentCollection(Collection<Document> documentCollection) {
this.documentCollection = documentCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Site)) {
return false;
}
Site other = (Site) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ru.fedd.entities.Site[ id=" + id + " ]";
}
}
Can you share your POJO class here?
You probably have to annotate your id of the POJO class with #GeneratedValue to notify it is auto generated. Then JPA will take care of the insertion.