Main method
EntityManagerFactory emf=Persistence.createEntityManagerFactory("manager1");
EntityManager em1=emf.createEntityManager();
EntityTransaction entityTransaction=em1.getTransaction();
entityTransaction.begin();
Person persons=JPA_basic_Example.setPerson();//fills all the fields of person
Credential cred=JPA_basic_Example.setCredential();//fills all fields of credentials
System.out.println("check1");
cred.setPerson(persons);
persons.setCredential(cred);
em1.persist(cred);
entityTransaction.commit();
em1.close();
emf.close();
Java Bean Credential oneToone Bidirectional with Person
public class Credential {
#Id
#Column(name ="credentialid")
private int credential_id;
private String UserName;
private String Password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="Personid")
private Person person;
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getCredential_id() {
return credential_id;
}
public void setCredential_id(int credential_id) {
this.credential_id = credential_id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Java Bean Person
#Entity
public class Person {
#Id
#Column(name ="Personid")
private int person_id;
//#Basic(optional = false)
//#Column(name ="Name", unique = true)
private String name;
#ElementCollection
#CollectionTable
List<String> contact=new ArrayList<String>();
private Address address=new Address();
#OneToOne(mappedBy = "person", orphanRemoval = true )
Credential credential ;
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getContact() {
return contact;
}
public void setContact(List<String> contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
}
Output Console
Hibernate:
insert
into
Person
(area, city, pincode, state, name, Personid)
values
(?, ?, ?, ?, ?, ?)
AFter this code stuck and nit moving forward nor showing any exceptions or errors
Related
I'm developing small Spring MVC application, and I have a problem with delete customer from mysql database. When I delete customer like a admin, customer disappears only in the customer table and remains in the authority and users tables. The question is how to repair it?
User.class
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int usersId;
private String username;
private String password;
private Boolean enabled;
private int customerId;
public int getUsersId() {
return usersId;
}
public void setUsersId(int usersId) {
this.usersId = usersId;
}
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 getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
}
#Entity
public class Authorities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int authoritiesId;
private String username;
private String authority;
public int getAuthoritiesId() {
return authoritiesId;
}
public void setAuthoritiesId(int authoritiesId) {
this.authoritiesId = authoritiesId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 5140900014886997914L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int customerId;
#NotEmpty(message = "Nazwa użytkownika nie może pozostać pusta!")
private String customerName;
#NotEmpty(message = "Uzupełnij adres email!")
private String customerEmail;
private String customerPhone;
#NotEmpty(message = "Nazwa użytkownika nie może pozostać pusta!")
private String username;
#NotEmpty(message = "Uzupełnij hasło!")
#Size(min = 6, max = 16, message = "Hasło musi zawierać od 6 do 16 znaków!")
private String password;
private boolean enabled;
#OneToOne(mappedBy = "customer", cascade = CascadeType.REMOVE)
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne(mappedBy = "customer", cascade = CascadeType.REMOVE)
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
#OneToOne( cascade = CascadeType.REMOVE, mappedBy = "customer")
#JoinColumn(name = "cartId")
#JsonIgnore
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
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 isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
#Controller
public class RegisterController {
#RequestMapping("/register")
public String registerCustomer(Model model) {
Customer customer = new Customer();
BillingAddress billingAddress = new BillingAddress();
ShippingAddress shippingAddress = new ShippingAddress();
customer.setBillingAddress(billingAddress);
customer.setShippingAddress(shippingAddress);
model.addAttribute("customer", customer);
return "registerCustomer";
}
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerCustomerPost(#Valid #ModelAttribute("customer") Customer customer, BindingResult result,
Model model) {
if (result.hasErrors()) {
return "registerCustomer";
}
List<Customer> customerList = customerService.getAllCustomers();
for (int i = 0; i < customerList.size(); i++) {
if (customer.getCustomerEmail().equals(customerList.get(i).getCustomerEmail())) {
model.addAttribute("emailMsg", "Email już istnieje w bazie danych!");
return "registerCustomer";
}
if (customer.getUsername().equals(customerList.get(i).getUsername())) {
model.addAttribute("usernameMsg", "Użytkownik o dane nazwie już istnieje w bazie!");
return "registerCustomer";
}
}
customer.setEnabled(true);
customerService.addCustomer(customer);
return "registerCustomerSuccess";
}
}
#Repository
#Transactional
public class CustomerDaoImpl implements CustomerDao {
#Autowired
private SessionFactory sessionFactory;
public void addCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
customer.getBillingAddress().setCustomer(customer);
customer.getShippingAddress().setCustomer(customer);
session.saveOrUpdate(customer);
session.saveOrUpdate(customer.getBillingAddress());
session.saveOrUpdate(customer.getShippingAddress());
Users newUser = new Users();
newUser.setUsername(customer.getUsername());
newUser.setPassword(customer.getPassword());
newUser.setEnabled(true);
newUser.setCustomerId(customer.getCustomerId());
Authorities newAuthority = new Authorities();
newAuthority.setAuthority("ROLE_USER");
session.saveOrUpdate(newUser);
session.saveOrUpdate(newAuthority);
newAuthority.setUsername(customer.getUsername());
Cart newCart = new Cart();
newCart.setCustomer(customer);
customer.setCart(newCart);
session.saveOrUpdate(customer);
session.saveOrUpdate(newCart);
session.flush();
}
public Customer getCustomerById(int id) {
Session session = sessionFactory.getCurrentSession();
Customer customer = (Customer) session.get(Customer.class, id);
session.flush();
return customer;
}
public List<Customer> getAllCustomers() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Customer ");
List<Customer> customerList = query.list();
return customerList;
}
public Customer getCustomerByUsername(String username) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Customer where username = ?");
query.setString(0, username);
return (Customer) query.uniqueResult();
}
public void deleteCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
session.delete(customer);
session.flush();
}
}
You have to add foreign key constraints between tables and set action as(on delete= cascade).
Your customer entity doesn't have any relationship with user and authority tables, then no delete is performed by jpa.
EDIT
In customer entity instead of username you could have
#OneToOne(mappedBy="username", cascadeType=CascadeType.REMOVE) private User user
The same for Authories entity:
#OneToOne(mappedBy="username", cascadeType=CascadeType.REMOVE) private User user
On your opinion ,the relationship between User and Customer is one to one.And you want to delete User when you delete the Customer .
First we have to explicit the relationship.
In the User Entity , i suggest you to remove the CustomerId , And add User user to Customer Entity.
And the Customer Entity will be :
private User user;
public void setUser(User user){
this.user = user;
}
#OneToOne
public User getUser(){
return this.user;
}
After that ,you can get the User by customer(userId),And when you want to delete the Customer ,you should get the User first,then delete Customer and delete that User
I want make a case, when user is authenticated by Spring Security and then he fill adres form I would like to automatically updated a foreign key column "adres_id" in user table. Please give me a tip how implement this in the most popular way
I how somethig like this
Address Table:
User Table:
Adres
#Entity
#Table(name="adres")
public class Adres {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
#OneToOne(mappedBy ="adres")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getStreet() {
return postcode;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
User
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="username", nullable=false)
private String username;
private String password;
private String email;
private Boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
private Adres adres;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
AdresDAO
#Repository
#Transactional
public class AdresDAOImpl implements AdresDAO{
#Autowired
SessionFactory sessionFactory;
public void addAdres(Adres adres) {
sessionFactory.getCurrentSession().save(adres);
}
public List<Adres> listAdres() {
return sessionFactory.getCurrentSession().createQuery("from Adres order by id").list();
}
public void removeAdres(int id) {
Adres adres = (Adres) sessionFactory.getCurrentSession().load(
Adres.class, id);
if (null != adres) {
sessionFactory.getCurrentSession().delete(adres);
}
}
public Adres getAdres(int id) {
return (Adres)sessionFactory.getCurrentSession().get(Adres.class, id);
}
public void editAdres(Adres adres) {
sessionFactory.getCurrentSession().update(adres);
}
}
AdresService
#Service
public class AdresServiceImpl implements AdresService{
#Autowired
AdresDAO adresDAO;
#Transactional
public void addAdres(Adres adres) {
adresDAO.addAdres(adres);
}
#Transactional
public void editAdres(Adres adres) {
adresDAO.editAdres(adres);
}
#Transactional
public List<Adres> listAdres() {
return adresDAO.listAdres();
}
#Transactional
public void removeAdres(int id) {
adresDAO.removeAdres(id);
}
#Transactional
public Adres getAdres(int id) {
return adresDAO.getAdres(id);
}
}
User unidirectional relation between User and Address if Address object does not supposed to know about its owner (generally it does not). I would prefer user id in Address table if a User have more than one Address (one-to-many relation).
But for your question you may design like that,
public class User{
...
#OneToOne(CascadeType.REMOVE)//this is for to remove address when user is removed
#JoinColumn(name="HOME_ADDRESS_ID")
private Address address;
...
}
and
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
//no user object here
public int getId() {
return id;
}
...
}
I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
I am doing a OneToMany relationship in a hibernate query. It's working fine but the donorId is not going to the blood table.
Donor Class:
#Entity
#Table(name = "DONOR")
public class Donor {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int donorId;
private String firstName;
private String lastName;
private int age;
private String cnic;
private String contactNumber;
private String homeNumber;
private String country;
private String city;
private String town;
private String streetNo;
private String houseNo;
private String email;
#OneToMany(mappedBy="donor")
private Set<Blood> blood;
public int getDonorId() {
return donorId;
}
public void setDonorId(int donorId) {
this.donorId = donorId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCnic() {
return cnic;
}
public void setCnic(String cnic) {
this.cnic = cnic;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Blood> getBlood() {
return blood;
}
public void setCity(Set<Blood> blood) {
this.blood = blood;
}
}
Blood Class:
#Entity
#Table(name = "BLOOD")
public class Blood {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int bloodId;
private String bloodType;
private int price;
#ManyToOne
#JoinColumn(name="donor_id")
private Donor donor;
public int getBloodId() {
return bloodId;
}
public void setBloodId(int bloodId) {
this.bloodId = bloodId;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Donor getDepartment() {
return donor;
}
public void setDonor(Donor donor) {
this.donor = donor;
}
}
Blood And Donor Object class:
public class BloodDonor {
private Donor donor;
private Blood blood;
public Donor getDonor() {
return donor;
}
public void setDonor(Donor donor) {
this.donor = donor;
}
public Blood getBlood() {
return blood;
}
public void setBlood(Blood blood) {
this.blood = blood;
}
}
BloodService Class:
public class BloodService {
SessionFactory sessionFactory = null;
public BloodDonor addNewBlood(BloodDonor bloodDonor){
try{
Blood blood = new Blood();
Donor donor = new Donor();
blood = (Blood)bloodDonor.getBlood();
donor = (Donor)bloodDonor.getDonor();
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(donor);
session.save(blood);
session.getTransaction().commit();
session.close();
}catch(Exception ex){
ex.printStackTrace();
}
return bloodDonor;
}
}
Blood Resource:
#Path("blood")
public class BloodResource {
BloodService bloodService = new BloodService();
#Path("new")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public BloodDonor addNewDonor(BloodDonor blood){
return bloodService.addNewBlood(blood);
}
}
Console:
Hibernate: select nextval ('hibernate_sequence')
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into DONOR (age, city, cnic, contactNumber, country, email, firstName, homeNumber, houseNo, lastName, streetNo, town, donorId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into BLOOD (bloodType, donor_id, price, bloodId) values (?, ?, ?, ?)
First:
Add CascadeType:
#OneToMany(cascade = CascadeType.ALL, mappedBy="donor")
private Set<Blood> blood;
Second:
Your Entities should be interconnected e.g. Donor's Set<Blood> should contain a link to Blood and Blood's field Donor should be set to that Donor instance.
So, lets try to interconnect them:
Session session = sessionFactory.openSession();
session.beginTransaction();
Donor donor = new Donor();
Blood blood = new Blood();
blood.setDonor(donor);
HashSet<Blood> bloods = new HashSet<Blood>();
bloods.add(blood);
donor.setBlood(bloods);
//set some another fields if you want or they are NOT NULL in database
session.save(donor); //blood should be saved automatically due to cascade
session.getTransaction().commit();
session.close();
This should work if everything is alright with your database structure.
Following is my Entity class
#Entity
#Table(name = "USER_DETAILS")
public class UserDetails {
#Id
private int userId;
#Column (name="USER_NAME")
private String userName;
#Temporal(TemporalType.DATE)
private Date date;
#ElementCollection
private Set<Address> streetAddress = new HashSet<Address>();
public Set<Address> getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(Set<Address> streetAddress) {
this.streetAddress = streetAddress;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Following is Address class
public class Address {
private String city;
private String pin;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}
And following is main class
public class HibernateMain {
public static void main(String[] args) {
Address address = new Address();
address.setCity("Pune");
address.setPin("1232");
Address homeAddress = new Address();
homeAddress.setCity("home_Pune");
homeAddress.setPin("home_1232");
UserDetails user = new UserDetails();
user.setUserId(3);
user.setUserName("Second user");
user.setDate(new Date());
user.getStreetAddress().add(address);
user.getStreetAddress().add(homeAddress);
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory(new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
Session session = sf.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Exception is thrown at run time
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: com.example.model.Address, at table: UserDetails_streetAddress, for columns: [org.hibernate.mapping.Column(streetAddress)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Collection.validate(Collection.java:315)
at org.hibernate.mapping.Set.validate(Set.java:40)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at com.example.hibernate.HibernateMain.main(HibernateMain.java:36)
I am using hibernate 4.3 and MySQL as database. If i dont use collection then it works for rest.What is wrong with code.
EDIT:
One other question.Am i using right code to get SessionFactory for my hibernate version as my IDE showing ServiceRegistryBuilder class as depricated.
Thanks for help.
The address class must be annotated with mapping annotations. Particularly, #Embeddable and if necessary #Column to map to the appropriate columns in the database.
#Embeddable
public class Address {
private String city;
private String pin;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}