Eclipse 'generate entities from tables' and 'many to one' relation - java

i am developing a simple Java EE application, that uses database. It has two tables (Admin and Session signature) connected with many to one relation.
When i used eclipse to generate entities from tables, my attribute that links both tables was generated like this:
//bi-directional many-to-one association to Admin
#ManyToOne
#JoinColumn(name="owner")
private Admin admin;
Problem is, my owner attribute is Integer in database, and it has been created as Admin type.
Now when i want to pass some Integer variable to input it to database i get error:
The method setAdmin(Admin) in the type Signaturesession is not applicable for arguments (int).
Or when i want to cast it to (Admin) like this (taking it from session):
(Admin)session.getAttribute("adminId")
I get Jboss Error:
javax.servlet.ServletException: java.lang.ClassCastException: java.lang.Integer cannot be cast to com.podpisy.entities.Admin
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
secure.SecurityCheckFilter.doFilter(SecurityCheckFilter.java:100)
I am sure that this can be done easy, but i'm just really bad using Java.
Thanks for any help.
EDIT:
My Admin.java class:
package com.podpisy.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name="admins")
#NamedQuery(name="Admin.findAll", query="SELECT a FROM Admin a")
public class Admin implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private String login;
private String password;
//bi-directional many-to-one association to Signature
#OneToMany(mappedBy="admin")
private List<Signature> signatures;
//bi-directional many-to-one association to Signaturesession
#OneToMany(mappedBy="admin")
private List<Signaturesession> signaturesessions;
public Admin() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Signature> getSignatures() {
return this.signatures;
}
public void setSignatures(List<Signature> signatures) {
this.signatures = signatures;
}
public Signature addSignature(Signature signature) {
getSignatures().add(signature);
signature.setAdmin(this);
return signature;
}
public Signature removeSignature(Signature signature) {
getSignatures().remove(signature);
signature.setAdmin(null);
return signature;
}
public List<Signaturesession> getSignaturesessions() {
return this.signaturesessions;
}
public void setSignaturesessions(List<Signaturesession> signaturesessions) {
this.signaturesessions = signaturesessions;
}
public Signaturesession addSignaturesession(Signaturesession signaturesession) {
getSignaturesessions().add(signaturesession);
signaturesession.setAdmin(this);
return signaturesession;
}
public Signaturesession removeSignaturesession(Signaturesession signaturesession) {
getSignaturesessions().remove(signaturesession);
signaturesession.setAdmin(null);
return signaturesession;
}
}
My Signaturesession.class:
package com.podpisy.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the signaturesession database table.
*
*/
#Entity
#NamedQuery(name="Signaturesession.findAll", query="SELECT s FROM Signaturesession s")
public class Signaturesession implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private String device;
private String name;
private int signatures;
private int time;
private String type;
private int users;
//bi-directional many-to-one association to Admin
#ManyToOne
#JoinColumn(name="owner")
private Admin admin;
public Signaturesession() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getDevice() {
return this.device;
}
public void setDevice(String device) {
this.device = device;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getSignatures() {
return this.signatures;
}
public void setSignatures(int signatures) {
this.signatures = signatures;
}
public int getTime() {
return this.time;
}
public void setTime(int time) {
this.time = time;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public int getUsers() {
return this.users;
}
public void setUsers(int users) {
this.users = users;
}
public Admin getAdmin() {
return this.admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
}

You should pass an Admin object which surely has an int id field.
So you've to make something like this
Admin myAdmin=new Admin(id,.. other properties);
mySignaturesession.setAdmin(myAdmin);
EDIT
Above is valid if you want to associate and Admin to your SignatureSession object. Instead if you have an Admin ojbect in Session you just have to execute
Admin anAdmin=(Admin)session.getAttibute("adminId");
Admin myAdmin=new Admin(id,.. other properties);
or
Admin myAdmin=new Admin();
myAdmin.setId(anId);
But, i repeat, it depends from what you have in the Session and which objects you handle.
And, as you look to be using JPA, dont forget to do something like em.persist or em.merge on your objects.
Maybe you should get a little deeper on how JPA works.

Related

Spring boot+jersey api+ JPA : failed to lazily initialize a collection of role

I am new with using spring boot + jersey api + JPA.
I hava three entity that uses one to many bidirectional mapping. When i used spring boot + jersey api+ JPA I get error :
failed to lazily initialize a collection of role: com.kavinaam.GSTbilling.entity.Country.states, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.kavinaam.GSTbilling.entity.City["states"]->com.kavinaam.GSTbilling.entity.States["countyId"]->com.kavinaam.GSTbilling.entity.Country["states"])
I have added my entity, dao , services and end point.
#Entity
#Table(name="country")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#Column(name="countryName")
private String countryName;
#OneToMany(mappedBy = "countyId",cascade = CascadeType.ALL)
private Set<States> states;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Set<States> getStates() {
return states;
}
public void setStates(Set<States> states) {
this.states = states;
}
}
My state class:
#Entity
#Table(name="states")
public class States implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#ManyToOne
#JoinColumn(name="countyId")
private Country countyId;
#Column(name="stateName")
private String stateName;
#OneToMany(mappedBy = "states", cascade = CascadeType.ALL)
private Set<City> city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Country getCountyId() {
return countyId;
}
public void setCountyId(Country countyId) {
this.countyId = countyId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Set<City> getCity() {
return city;
}
public void setCity(Set<City> city) {
this.city = city;
}
}
My city class:
#Entity
#Table(name="cities")
public class City implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#ManyToOne
#JoinColumn(name="stateId")
private States states;
#Column(name="cityName")
private String cityName;
#Column(name="zip")
private String zip;
public void setId(int id) {
this.id = id;
}
public void setZip(String zip) {
this.zip = zip;
}
public States getStates() {
return states;
}
public void setStates(States states) {
this.states = states;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getZip() {
return zip;
}
public int getId() {
return id;
}
}
My DAO:
#Transactional
#Repository
public class GSTCityDAO implements IGSTCityDAO {
#PersistenceContext
private EntityManager entityManager;
//#SuppressWarnings("unchecked")
#Override
public List<City> getAllCities() {
//Session session = sessionFactory.getCurrentSession();
String hql = "FROM City as ct ORDER BY ct.id";
List<City> l = entityManager.createQuery(hql,City.class).getResultList();
return l;
}
#Override
public City getCityById(int cityId) {
return entityManager.find(City.class, cityId);
}
#SuppressWarnings("unchecked")
#Override
public List<City> getCityByStateId(States stateId) {
String getcitybystate = " FROM City as c WHERE c.states = ?";
return (List<City>) entityManager.createQuery(getcitybystate).setParameter(1, stateId).getResultList();
}
#Override
public void addCity(City city) {
entityManager.persist(city);
}
#Override
public void updateCity(City city) {
City cityctl = getCityById(city.getId());
cityctl.setCityName(city.getCityName());
cityctl.setZip(city.getZip());
cityctl.setStates(city.getStates());
entityManager.flush();
}
#Override
public void deleteCity(int cityId) {
entityManager.remove(getCityById(cityId));
}
#Override
public boolean cityExists(String name, String zip) {
String hql = "FROM City WHERE cityName = ? and zip = ?";
int count = entityManager.createQuery(hql).setParameter(1,name).setParameter(2, zip).getResultList().size();
return count > 0 ? true : false;
}
}
Services:
#Service
public class GSTCityService implements IGSTCityService {
#Autowired
private IGSTCityDAO cityDAO;
#Override
public List<City> getAllCities() {
List<City> l = cityDAO.getAllCities();
Hibernate.initialize(l);
return l;
}
public List<City> getCityByStateId(States stateId) {
return cityDAO.getCityByStateId(stateId);
}
#Override
public City getCityById(int cityId) {
City city = cityDAO.getCityById(cityId);
return city;
}
#Override
public synchronized boolean addCity(City city) {
if(cityDAO.cityExists(city.getCityName(), city.getZip())){
return false;
}else{
cityDAO.addCity(city);
return true;
}
}
#Override
public void updateCity(City city) {
cityDAO.updateCity(city);
}
#Override
public void deleteCity(int cityId) {
cityDAO.deleteCity(cityId);
}
}
End Point:
#Component
#Path("/")
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
#Autowired
private IGSTCityService cityService;
#GET
#Path("/hi")
#Produces(MediaType.APPLICATION_JSON)
public Response hello(){
return Response.ok("Hello GST").build();
}
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllDate(){
List<City> list = cityService.getAllCities();
for(City city: list){
System.out.println(city);
}
return Response.ok(list).build();
}
#GET
#Path("/test/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllDateBySome(#PathParam("id") Integer id){
States state = new States();
state.setId(id);
List<City> list = cityService.getCityByStateId(state);
return Response.ok(list).build();
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getDataById(#PathParam("id")Integer id){
City citl = cityService.getCityById(id);
return Response.ok(citl).build();
}
#POST
#Path("/add")
#Consumes(MediaType.APPLICATION_JSON)
public Response addData(City city){
boolean isAdded = cityService.addCity(city);
if(!isAdded){
return Response.status(Status.CONFLICT).build();
}
return Response.created(URI.create("/gst/"+ city.getId())).build();
}
#PUT
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response updateCountry(City city){
cityService.updateCity(city);
return Response.ok(city).build();
}
#DELETE
#Path("/{id}")
#Consumes(MediaType.APPLICATION_JSON)
public Response deleteCountry(#PathParam("id")Integer id){
cityService.deleteCity(id);
return Response.noContent().build();
}
}
I am using import org.springframework.transaction.annotation.Transactional; for transnational in DAO. Also I can not use #PersistenceContext(type=PersistenceContextType.EXTENDED) and fetch type Eager because I get error of Maximum stack size exceeded
I solved it by using the #JsonBackReference on OneToMany relationship. The problem is with the Serialization and Deserialization.
" the property annotated with #JsonManagedReference annotation is handled normally (serialized normally, no special handling for deserialization) and the property annotated with #JsonBackReference annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link."
You should do one or both of the following:
1) Move the #Transactional from DAO to Service. Thats a good idea in general as usually are still processing the result entities in some way on that layer.
2) Fetch the dependencies in the queries explicitly:
select ct FROM City as ct inner join fetch ct.states s ORDER BY ct.id

Spring boot , CrudRepository findbyid or findOne is not getting One to many table details of role table

#Entity
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String email;
private String password;
private String username;
#Transient
private String passwordConfirm;
//bi-directional many-to-one association to Role
#ManyToOne(fetch=FetchType.LAZY ,cascade = {CascadeType.PERSIST})
private Role role;
public User() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#Transient
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}
#Entity
#NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String name;
//bi-directional many-to-one association to User
#OneToMany(fetch=FetchType.LAZY, mappedBy="role", cascade = {CascadeType.PERSIST})
private List<User> users;
public Role() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public User addUser(User user) {
getUsers().add(user);
user.setRole(this);
return user;
}
public User removeUser(User user) {
getUsers().remove(user);
user.setRole(null);
return user;
}
}
public interface UserRepository extends CrudRepository <User, Long> {
public UserDto getUserDetailsById(Long userId) throws commonException {
//ArrayList<UserDto> arr = new ArrayList<>();
User user = userRepository.`findOne`(userId);
UserDto userDto = new UserDto();
userDto.setId(user.getId());
userDto.setUsername(user.getUsername());
userDto.setEmail(user.getEmail());
userDto.setPassword(user.getPassword());
userDto.setRoleId(user.getRole().getId());
userDto.setRoleName(user.getRole().getName());
// arr.add(userDto);
return userDto;
}
find by Id is not getting role details by using user object.lazy initialization is not happening.When I use to get user ID from user object, I can not get role details.
userDto.setRoleId(user.getRole().getId()); is having null value
In your User entity, you have configured the Role collection to load lazily. Therefore when you first call user.getRole(), you get a proxy object. If you want to call methods on the proxy object that need to fetch data, you should initialize the proxy. There is a technique to initialize it. Try the following:
Before the following line of code
userDto.setRoleId(user.getRole().getId());
add the following;
user.getRole().size();
For situations where you know that you need a particular association, its generally recommended that you specify that the association be join-fetched.
If the association is optional, you'd use something like:
FROM User u LEFT JOIN FETCH u.role WHERE u.id = :userId
If the association is not-optional, you could improve the above by specifying an inner join like:
FROM User u JOIN FETCH u.role WHERE u.id = :userId
With Spring data, you can use the #Query annotation on methods and specify the JPQL/HQL above to suit your needs.

In Spring mvc How to add add set values to mysql

My goal :
In Spring MVC I have to save mobile phone contact list into database.
example:
phone1 sonia 2554654 work
2554654 home
multiple phone_number with multiple phone_Number type
contacts table
id,
contact_name
phone_number
phone_type
in my java class I have
public class ContactMobile {
private String type;
private String number;
public ContactMobile() {
}
public ContactMobile(String type, String number) {
super();
this.type = type;
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
and here I use SET for phone number and type
#Entity
#Table(name = "_contact")
public class MobileContact {
private String id;
private String fullname;
private Set<ContactMobile> mobileNumbers;
public MobileContact(String fullname, Set<ContactMobile> mobileNumbers) {
super();
this.fullname = fullname;
this.mobileNumbers = mobileNumbers;
}
#Id
#Column(name = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "fullname")
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
public void setMobileNumbers(Set<ContactMobile> mobileNumbers) {
this.mobileNumbers = mobileNumbers;
}
public MobileContact() {
super();
}
}
I am using hibernate to store data..
my question is in my MobileContact class in
public Set<ContactMobile> getMobileNumbers() {
return mobileNumbers;
}
what annotation I have to use here to save multiple phonenumbers?
The MobileContact entity has many ContactMobile, it is a OneToMany relation. In your ContactMobile table, you should has a field for the id of MobileContact, like mobile_contact_id, and set the join column on that field as below in your ContactMobile:
#OneToMany(fetch = FetchType.LEZY)
#JoinColumn(name = "mobile_contact_id")
private Set<ContactMobile> mobileNumbers;
You can get the detail about the relation in this.
You can use the Embeddables (instead of Entities) for very simple value objects like MobileContact (then they do not need an ID, and the are no just simple value objects without own identity)
#Embeddable
public class ContactMobile {...
//implement an equals and hashcode method!
}
public class MobileContact {
...
#ElementCollection
private Set<ContactMobile> mobileNumbers;
...
}
#See Java Persistence/ElementCollection

get dbref from document in Mongo using Java

I cannot get dbRef object from Mongo. In my entity package I have a User class with a Parent class inheriting.
Here is the User class:
public class User {
#Id
private ObjectId id;
#DBRef
private Account account;
private String name;
public String getId() {
if (id != null) {
return id.toStringMongod();
}
return null;//no id
}
public void setId(ObjectId objectId) {
this.id = objectId;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
As you can see above, I am putting an object of Account here.
My Parent class simply extends User:
#Document
public class Parent extends User {
#JsonProperty("is_activated")
private boolean isActivated;
public boolean isActivated() {
return isActivated;
}
public void setActivated(boolean isActivated) {
this.isActivated = isActivated;
}
}
Note: nothing magic with isActivated.
In my ParentDaoImpl class:
#Service
public class ParentDaoImpl extends AbstractDaoImpl implements ParentDao {
#Override
public Parent getParentByLogin(String login) {
Query query = new Query(Criteria.where("login").is(login));
return mongoOperations.findOne(query, Parent.class, "parents");
}
}
The problem is that if I call getParentByLogin method, it returns evertyning but Account field is null. Maybe findOne doesn't give dbRef inside. I think in relational Databases, there would be something like join. I want my method to give me account field as well.
Thanks for your help!
Can you try something like this.
....
#Field("fieldName")
#DBRef(collection = "mongoCollectionName")
private Account account;
....

Not whole entity being retrieved in ejb3

I have three classes which are connected to each other. Order, OrderDetail and Product. When I do in my JPA project the following:
#Override
public Order getOrderById(String orderID) {
Order order = (Order)
em.createQuery("select A from Order A where A.orderId = ?1")
.setParameter(1, orderID)
.getSingleResult();
return order;
}
all the info is retrieved. However, when I move it to the ebj project. I only get Order and that's it. All classes are however included in both the persistence.xml files (JPA and ejb3). Why is that and how should i solve it? The three classes are displayed underneath. I'm using Oracle Weblogic 10.3.3. I tried restarting and clearing the server but that didn't work.
*package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;*
/**
* The persistent class for the orders database table.
*
*/
#Entity
#Table(name="orders")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="order_id")
private String orderId;
#Column(name="cc_expiry")
private String ccExpiry;
#Column(name="cc_name")
private String ccName;
#Column(name="cc_number")
private String ccNumber;
#Column(name="delivery_address")
private String deliveryAddress;
#Column(name="delivery_name")
private String deliveryName;
#Column(name="delivery_surname")
private String deliverySurname;
private String status;
//bi-directional many-to-one association to OrderDetail
#OneToMany(mappedBy="order", cascade=CascadeType.PERSIST)
private List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
public void addOrUpdateOrderDetail(Product product) {
this.orderDetails.add(new OrderDetail(product));
}
public Order() {
}
public String getOrderId() {
return this.orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getCcExpiry() {
return this.ccExpiry;
}
public void setCcExpiry(String ccExpiry) {
this.ccExpiry = ccExpiry;
}
public String getCcName() {
return this.ccName;
}
public void setCcName(String ccName) {
this.ccName = ccName;
}
public String getCcNumber() {
return this.ccNumber;
}
public void setCcNumber(String ccNumber) {
this.ccNumber = ccNumber;
}
public String getDeliveryAddress() {
return this.deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public String getDeliveryName() {
return this.deliveryName;
}
public void setDeliveryName(String deliveryName) {
this.deliveryName = deliveryName;
}
public String getDeliverySurname() {
return this.deliverySurname;
}
public void setDeliverySurname(String deliverySurname) {
this.deliverySurname = deliverySurname;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public List<OrderDetail> getOrderDetails() {
return this.orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
}
package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the order_details database table.
*
*/
#Entity
#Table(name="order_details")
public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L;
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private BigDecimal price;
private int quantity;
//bi-directional many-to-one association to Order
#ManyToOne
#JoinColumn(name="order_id")
private Order order;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="product_id")
private Product product;
#Id
private int product_id;
public OrderDetail() {
}
public OrderDetail (Integer ProductId,Product product,Integer productQuantity,BigDecimal price, Order order) {
this.price= price;
this.product_id = ProductId;
this.product = product;
this.quantity = productQuantity;
this.order = order;
}
public OrderDetail(Product product1) {
product_id = product1.getCategoryId();
price = product1.getPrice();
quantity = 1;
product = product1;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Order getOrder() {
return this.order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
}
package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the products database table.
*
*/
#Entity
#Table(name="products")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="product_id")
private int productId;
#Column(name="category_id")
private int categoryId;
#Lob
private String descr;
private BigDecimal price;
#Column(name="product_name")
private String productName;
private int quantity;
public Product() {
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getCategoryId() {
return this.categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getDescr() {
return this.descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
As it appeared I had to add transaction type JTA to the ejb's web.xml file.
I don't understand what you mean by "moving the code from the JPA project to the EJB project). Also, can you be a bit more specific about your problem? What makes you say that the objects are not loaded? Where is the code that invokes getOrderById()?
I suspect that it is in the web tier. In that case, I suspect that you may have an issue with the fetch type. By default, it is defined as LAZY (vs EAGER).
This means that JPA will initially load only the root object. It is when you try to access the linked objects that JPA will issue other requests. That will be transparent to the developer, with an important requirement: it will work only when you are in EJB tier. If you have returned the root object to the web tier, then it is "detached" and is not controlled by JPA any more. This means that if the dependent objects have not been loaded, then you will get null values when accessing them (follow-up requests will not be sent to the DB, because JPA is out of the loop).

Categories