Before I was getting NullPointerException in this line
EntityManager manager = emf.createEntityManager();
but I fixed it by adding one line above
emf = Persistence.createEntityManagerFactory("main");
Now I am getting NullPointerException in this line
transaction.begin();
I can't understand why. I was trying to take it from the try catch block but was getting the same result. Also in the finally I tried to add emf.close(); but the error doesn't get fixed. Also, I include #Named annotation because someone suggested me to do that.
import java.io.Serializable;
import javax.inject.Named;
import javax.inject.Inject;
import java.sql.*;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery ;
import javax.transaction.UserTransaction;
import javax.transaction.RollbackException;
import javax.persistence.criteria.*;
import java.util.List;
import java.util.*;
#Named
public class UserManager implements Serializable{
#PersistenceUnit(unitName="main")
private EntityManagerFactory emf;
#Resource
private UserTransaction transaction;
public UserManager() {}
public UserTransaction getTransaction() { return transaction; }
public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }
public void addUser(User v) throws Exception {
emf = Persistence.createEntityManagerFactory("main");
EntityManager manager = emf.createEntityManager();
boolean commit;
try {
transaction.begin();
manager.joinTransaction();
commit = false;
try {
manager.persist(v);
transaction.commit();
commit = true;
}finally {
if(commit==false){
transaction.rollback();
}
}
}finally {
manager.close();
//emf.close();
}
}
#Named("subBean")
#RequestScoped
public class UserBean implements Serializable{
private List<User> users;
private UserManager vm;
private User v;
private int total;
public UserBean() {
this.total= 0;
users = new ArrayList<User>();
vm = new UserManager();
v = new User();
}
public String addUserAction() throws Exception {
vm.addUser(v);
users = getUsers();
return "submit1";
}
//getters and setters
}
As noted in my comment, the problem is that you're creating an instance of UserManager bean manually and CDI cannot inject the variables. This is noted here:
#Named("subBean")
#RequestScoped
public class UserBean implements Serializable{
//variable is just declared...
private UserManager vm;
public UserBean() {
//and here you're initializing it manually...
vm = new UserManager();
}
//rest of your code...
}
Let CDI do its work by injecting the variable:
#Named("subBean")
#RequestScoped
public class UserBean implements Serializable{
//variable is just declared
//and notify CDI it should inject an instance when creating an instance of the client class
#Inject
private UserManager vm;
public UserBean() {
//no need to initialize it ever
//vm = new UserManager();
}
//rest of your code...
}
By doing this, you won't need to create any field that should be injected in your other bean either, which means you don't need to initialize emf field manually:
//this line should be commented as well...
//emf = Persistence.createEntityManagerFactory("main");
Related
I have a legacy app using JEE5 , I add a class "People" and add "by hand" in the database a lot of records (people only has peopleid and a string peopledesc)
If I use the method getAllPeople() I get the list correctly populated, every data is there
But when I try to persist a new record by code using persistPeople(People pep) It just does nothing
The system.out.println shows the description added to the object so the new created object is passed to the method, but it is not persisted in the database :(
No error is shown in the console output.
People.java
#Entity
public class People implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idpeople;
private String desc;
persistence.xml
<persistence-unit name="PersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entities.People</class>
......
PeopleDAOImPL.JAVA
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import residencias.dominio.Renovacion;
#Stateless
public class PeopleDAOImpl implements PeopleDAO {
//EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnit");
#PersistenceUnit(unitName="PersistenceUnit")
private EntityManagerFactory emf;
#Override
public void persistPeople(People pep) {
EntityManager em = emf.createEntityManager();
System.out.println("description is :"+pep.getDesc());
em.persist(pep);
}
#Override
public List<People> getAllPeople() {
EntityManager em = emf.createEntityManager();
List<People> results = new ArrayList();
Query queryPrincipal;
try {
queryPrincipal = em.createQuery("SELECT p FROM People p");
results = queryPrincipal.getResultList();
return results;
} catch (Exception e) {
System.out.println(results.size());
return results;
} finally {
if (em != null) {
emf.close();
em.close();
}
}
}
While during the invocation of a query, you are not obliged to be running within a transaction, when you try to persist / update state of an entity you must be running that particular action within a transaction boundary.
In your case you could use following configuration:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class PeopleDAOImpl implements PeopleDAO {
#PersistenceUnit(unitName="PersistenceUnit")
private EntityManagerFactory emf;
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void persistPeople(People pep) {
EntityManager em = emf.createEntityManager();
System.out.println("description is :"+pep.getDesc());
em.persist(pep);
}
I am learning to write a UnitTest for my JSF project which has ManangedBeans and Session Beans
I have a problem invoking the EJB from Mockito test
package Test;
import ejb.CountrySession;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named(value = "countryMB")
#ViewScoped
public class CountryMB implements Serializable {
#EJB
private CountrySession countSession;
//
private String countryName;
//
private StatusMsg msg;
public CountryMB() {
}
public void setMsg(StatusMsg msg) {
this.msg = msg;
}
public void setCountSession(CountrySession countSession) {
this.countSession = countSession;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public void ajaxAll() {
}
public void saveCountry() {
if (countryName != null && !countryName.trim().isEmpty()) {
boolean chk = countSession.chkCountry(countryName);
if (!chk) {
chk = countSession.addCountry(countryName);
if (chk) {
msg.addInfo("Add Country", "New Country added");
} else {
msg.addError("Add Country", "Unable to add Country");
}
} else {
msg.addWarn("Add Country", "Country already exists");
}
} else {
msg.addWarn("Add Country", "Required parameter not available");
}
}
}
Now in my Test Code i have the following
package Test;
import ejb.CountrySession;
import entities.Country;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class CountryMBTest {
#Mock
private CountryMB countryMB;
#Mock
private StatusMsg sm;
#Mock
private CountrySession countSession;
#Mock
private EntityManager em;
#Mock
private Query qry;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
countryMB = new CountryMB();
countryMB.setMsg(sm);
countryMB.setCountSession(countSession);
}
#After
public void after() {
countryMB = null;
}
#Test
public void infoCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addInfo("Add Country", "New Country added");
}
#Test
public void errorCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addError("Add Country", "Unable to add Country");
}
#Test
public void warnCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addWarn("Add Country", "Country already exists");
}
#Test
public void chkCountSave() {
List<Country> countLst = null;
Country dum = mock(Country.class);
EntityManager em = mock(EntityManager.class);
Mockito.when(em.find(Country.class, 111)).thenReturn(dum);
CountrySession cs = Mockito.mock(CountrySession.class);
Mockito.when(cs.chkCountry("Test")).thenCallRealMethod();
Mockito.when(cs.getEm()).thenReturn(em);
String name = "Test";
Assert.assertNull(cs.chkCountry(name));
}
}
My table has only one Record pk=1, Country=Test
The above test code never check the session beans, it just throw
java.lang.NullPointerException
at ejb.CountrySession.chkCountry(CountrySession.java:67)
at Test.CountryMBTest.chkCountSave(CountryMBTest.java:112)
And for infoCountrySave() & warnCountrySave() it just never check the supplied value in the database.
As i have never used any UnitTest earlier so i really don't know if what i am doing is correct, moreover i could not figure out any working code by googling.
It will be of great help if anyone can guide me to some resource available online or even let me know what is that i need to correct to get the above mockito test work with the ejb part.
Change #Mock with #InjectMocks for
private CountryMB countryMB
and when you get java.lang.NullPointerException. Mostly you miss inject some class or some dependency on by called when
Okay— I am assuming I am making a very obvious mistake here— but I can’t seem to find my answer through the several Google/SO searches I have done. My background with Java programming is heavily JSF based, and at work I only have experience using Faces to manage my beans (using the #Managed annotation). However, I am working on a personal project in which I am trying to use CDI for the first time. I am having trouble injecting a Service bean into a SessionScoped controller bean… It’s odd because I inject the same service bean into a different RequestScoped bean no problem… I don’t see what I am missing. I have the SessionScoped bean implementing Serializable, yet I am still getting the following error when I try to deploy, ONLY once I have added an #Inject variable to the bean (without which the bean will be pretty useless…): Caused by: org.apache.webbeans.exception.WebBeansConfigurationException: Passivation capable beans must satisfy passivation capable dependencies. Here’s a bit of my service and controller beans code:
UserService.java
import ds.nekotoba.model.User;
import java.util.Date;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import org.apache.deltaspike.jpa.api.transaction.Transactional;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.HashingPasswordService;
import org.apache.shiro.crypto.hash.Hash;
#Named
#Transactional//Makes all methods in bean transactional
public class UserService {
#Inject
private EntityManager em;
public User findById(Long id) {
return em.find(User.class, id);
}
public User findByUsername(String username) {
return em.createNamedQuery("User.findByUsername", User.class)
.setParameter("username", username)
.getSingleResult();
}
public User find(String username, String password) {
List<User> found = em.createNamedQuery("User.find", User.class)
.setParameter("username", username)
.setParameter("password", password)
.getResultList();
return found.isEmpty() ? null : found.get(0);
}
#Produces
#Named("users")
#RequestScoped
public List<User> list() {
return em.createNamedQuery("User.list", User.class).getResultList();
}
public Long create(User user) {
….
}
public void update(User user){
em.merge(user);
}
public void delete(User user){
em.remove(em.contains(user) ? user : em.merge(user));
}
}
LoginController.java Note: The #Inject calls in this bean work no problem!
import ds.nekotoba.model.User;
import ds.nekotoba.service.UserService;
import ds.nekotoba.util.Globals;
import java.io.IOException;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.omnifaces.util.Faces;
import org.omnifaces.util.Messages;
#Named(value="login")
#RequestScoped
public class LoginController {
public LoginController() {
}
#Inject ProfileController profile;
#Inject UserService userService;
//Variables
private String username;
private String password;
private boolean remember;
//<editor-fold desc="Getters/Setters">
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRemember() {
return remember;
}
public void setRemember(boolean remember) {
this.remember = remember;
}
//</editor-fold>
public void submit() throws IOException {
try {//Attempt login
SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));
} catch (AuthenticationException ae) {
Messages.addGlobalError("不明なユーザ、また試してみてください。");
ae.printStackTrace();
}
//If successful, set User in ProfileController, get full user info
if(SecurityUtils.getSubject().isAuthenticated()){
User user = new User();
user.setUsername(username);
user.setPassword(password);
profile.setUserInfo(user);
//profile.refreshUserInfo(); //COMMENTED OUT DUE TO ERROR INJECTED IN ProfileController.java
}
//Redirect to intended page
SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : Globals.HOME_URL);
}
}
ProfileController.java (The error mentioned above manifests once I use any #Inject calls in this bean…)
import ds.nekotoba.model.User;
import ds.nekotoba.service.UserService;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
#Named(value="profile")
#SessionScoped
public class ProfileController implements Serializable {
#Inject UserService userService;//CAUSES ERROR MENTIONED ABOVE
//Variables
private User userInfo;
public ProfileController() {
}
public void refreshUserInfo() {
userInfo = userService.findByUsername(userInfo.getUsername());
}
//<editor-fold desc="Getters/Setters">
public User getUserInfo() {
return userInfo;
}
public void setUserInfo(User userInfo) {
this.userInfo = userInfo;
}
//</editor-fold>
}
Like I said, I am a new-comer to CDI injection, so I am sure I am missing something obvious… I just can’t figure it out. Any help would be greatly appreciated.
Other Project Info:
JSF 2.2
JPA 2.0
TomEE 1.7.1
OmniFaces 1.8.1
Apache Shiro 1.3.0-SNAPSHOT
Apache DeltaSpike (could this be a conflicting point?)
Foo implements Serializable is necessary but not sufficient for Foo to be serializable. All members of Foo also have to be serializable.
In your case, ProfileController is serializable, but its UserService member is not.
I am beginner of Hibernate4. I am configured Play 2.2.4 with Hibernate 4.3.6 entitymanager and write a test application. So, I have Entity class Subject.java
package models.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.Table;
import play.data.validation.Constraints;
#Entity
#Table(name="subjects")
public class Subject {
#Id
#Column(name="sub_pcode")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="sub_name")
#Constraints.Required
public String name;
public int getId() {
return id;
}
public Subject() {
id = 0;
}
public void save() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
if (id == 0) {
em.persist(this);
} else {
em.merge(this);
}
em.getTransaction().commit();
em.close();
}
public void delete() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Subject tmpSubject = em.find(Subject.class, id);
if (tmpSubject != null) {
em.remove(tmpSubject);
}
em.getTransaction().commit();
em.close();
}
public static Subject get(int id) {
Subject result;
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
result = em.find(Subject.class, id);
em.getTransaction().commit();
em.close();
return result;
}
#SuppressWarnings("unchecked")
public static List<Subject> fetchAll() {
List<Subject> result = new ArrayList<>();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Query q = em.createQuery("SELECT s FROM Subject s");
result = q.getResultList();
em.getTransaction().commit();
em.close();
return result;
}
}
And controller class Application.java
package controllers;
import models.entities.Subject;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import views.html.list;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result addSubject() {
Subject s = new Subject();
s.name = "test subject";
s.save();
return ok(list.render(Subject.fetchAll()));
}
public static Result deleteSubject(int id) {
Subject s = Subject.get(id);
if (null != s) {
s.delete();
}
return ok(list.render(Subject.fetchAll()));
}
public static Result updateSubject(int id) {
Subject s = Subject.get(id);
if (null != s) {
s.name = "new subject";
s.save();
}
return ok(list.render(Subject.fetchAll()));
}
}
All I want is to ask a few questions:
Why I can merge entity (in save() method) without attaching, but
if I wand to delete entity (by the delete() method) - I need to
find entity first or I have an exception about deleting detached
entity?
Seems like from controller classess I can use JPA.em() with
#Transactional annotation to simplify work with hibernate. Is any
simplest way to work with hibernate transactions and entitymanagers
from non-controller classess?
If my code bad-styled, can anybody give me good advice about strategy of
hibernate usage and so on?
Best regards. Thanks for your advices and answers.
Your EntityManagerFactory emf should not be created every time. EntityManagerFactory are thread safe and you should use it as static. If create it every time your performance will drop.
Entity should not handle transactions, they are used only to reflect the database data. The correct way of using an Entity would be in a repository/DAO classes.
Why are you doing id = 0; in your constructor? The default is already 0.
Do not open a transaction in a Controller. Controller should handle only what gets in and what gets out of the project. If you add transaction in it you will be adding unnecessary complexity and increasing the coupling of your code. You could use the pattern OpenSessionInView, EJBs Components or Injection/AOP transaction controller.
To delete an entity you will need to attach it first. You could use the getReference method: Entity justId = entityManager.getReference(Entity.class, ID).
Take a look at this material that will help you understand about the JPA basics: http://uaihebert.com/jpa-mini-book-first-steps-and-detailed-concepts/
In a servelt, I try to call the session bean method to insert data to database via JPA. The insert process is written in the session bean.
I tried another example, which I select data from DB. The "select" works good. But I have no idea that why insert does not work.
The error information is:
HTTP Status 500
description: The server encountered an internal error () that prevented it from fulfilling this request.
exception: javax.ejb.EJBException
note: The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.0.1 logs.
I think there is something wrong with "tx.commit()", when I comment it then there is no error. But I do not know what the exactly problem.
Here is the bean class
#Stateless
#LocalBean
public class testSession {
public testSession() {
// TODO Auto-generated constructor stub
}
public void insertData(){
EntityManagerFactory emf;
EntityManager em;
//the Entity Class-Category
Category cat=new Category();
//set value
cat.setId(5);
cat.setName("test cat");
//the "test" is the persist unit in persistence.xml
emf=Persistence.createEntityManagerFactory("test");
em=emf.createEntityManager();
EntityTransaction tx=em.getTransaction();
tx.begin();
em.persist(cat);
tx.commit();
em.close();
emf.close();
}
}
In the servlet
#WebServlet("/testServlet")
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
testSession ts;
public testServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.print("<html><body>");
//call the method in the session bean to insert data
ts.insertData();
out.print("</body></html>");
}
}
you need Injection via #PersistenceContext
The EntityManager itself is created by the container using the information in the persistence.xml, so to use it at runtime, we simply need to request it be injected into one of our components. We do this via #PersistenceContext
The #PersistenceContext annotation can be used on any CDI bean, EJB, Servlet, Servlet Listener, Servlet Filter, or JSF ManagedBean. If you don't use an EJB you will need to use a UserTransaction begin and commit transactions manually. A transaction is required for any of the create, update or delete methods of the EntityManager to work.
Example:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
#LocalBean
public class testSession {
#PersistenceContext(unitName = "MyUNIT_PERSIS_IMPORTANT_View_THE_persistence.XML")
private EntityManager entityManager;
public testSession() {
// TODO Auto-generated constructor stub
}
public void insertData(){
//the Entity Class-Category
Category cat=new Category();
//set value
cat.setId(5);
cat.setName("test cat");
entityManager.persist(cat);
}
}
Reference
http://tomee.apache.org/examples-trunk/injection-of-entitymanager/
I have used maven to this demo
Demo
https://mega.co.nz/#!AxtRVQzB!MdwwOXA1e_VayWgwIdxGdREhd69QDb6la0yT0mLMaKA
to url to of servlet this
http://<HOST>/use-session-bean-to-insert-data-with-jpa/testServlet
SQL create
CREATE TABLE category (
id INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200),
PRIMARY KEY (id));
Persistence.xml
...
<persistence-unit name="test" transaction-type="JTA">
..
Java Servlet
import com.mycompany.ejb.testSession;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author I2B Boris
*/
#WebServlet(name = "testServlet", urlPatterns = {"/testServlet"})
public class testServlet extends HttpServlet {
#EJB
testSession ts;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("<html><body>");
//call the method in the session bean to insert data
ts.insertData();
out.print("</body></html>");
}
}
Java EJB
package com.mycompany.ejb;
import com.mycompany.entities.Category;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author I2B Boris
*/
#Stateless
#LocalBean
public class testSession {
#PersistenceContext(unitName = "test")
private EntityManager entityManager;
public void insertData() {
//the Entity Class-Category
Category cat = new Category();
//set value
cat.setId(5);
cat.setName("test cat");
entityManager.persist(cat);
}
}
Entity
package com.mycompany.entities;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author I2B Boris
*/
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 200)
#Column(name = "name")
private String name;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
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;
}
#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 Category)) {
return false;
}
Category other = (Category) 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.mycompany.entities.Category[ id=" + id + " ]";
}
}