Powered by Blogger.
Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Friday, 12 December 2014

Delete Data From Many-to-many Relationship


CustomerEntity class


@Entity(name = "CUSTOMER")
public class CustomerEntity {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customerid-gen")
   @SequenceGenerator(name = "customerid-gen", sequenceName = "CUSTOMER_SEQ"
      allocationSize = 1, initialValue = 0)

   @Column(name = "CUSTOMER_ID")
   private Integer id;

   private String customerName;

   @ManyToMany(cascade ={CascadeType.ALL})
   @JoinTable(name = "CUST_PHONE"
      joinColumns = @JoinColumn(name = "CUSTOMER_ID"
                                 referencedColumnName = "CUSTOMER_ID"), 
   inverseJoinColumns = @JoinColumn(name = "PHONE_ID"
                                 referencedColumnName = "PHONE_ID"))
   private List<PhoneNumberEntity> phones = new ArrayList<PhoneNumberEntity>();

}


PhoneNumberEntity class
@Entity(name = "PHONE")
public class PhoneNumberEntity {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "phoneid-gen")
   @SequenceGenerator(name = "phoneid-gen", sequenceName = "PHONE_SEQ"
      allocationSize = 1, initialValue = 0)
   @Column(name = "PHONE_ID")
   private Integer id;

   private String phNumber;

   @ManyToMany(cascade ={CascadeType.ALL})
   @JoinTable(name = "CUST_PHONE", joinColumns = @JoinColumn(name = "PHONE_ID",
                   referencedColumnName = "PHONE_ID"),
              inverseJoinColumns = @JoinColumn(name = "CUSTOMER_ID"
                     referencedColumnName = "CUSTOMER_ID"))
   private List<CustomerEntity> customers;

}


Testing class

CustomerEntity entity = new CustomerEntity("Shambhu");
entity.getPhones().add(new PhoneNumberEntity("(8837199181"));
entity.getPhones().add(new PhoneNumberEntity("(8981518899"));
Integer id = emService.persistCustomer(entity);
             
CustomerEntity customerEntity=emService.findCustomerById(id);
             
List<PhoneNumberEntity> phones= customerEntity.getPhones();
             
for(PhoneNumberEntity entity2:phones){
       System.out.println("Deleting phone id :"+entity2.getId());
       emService.deletePhone(entity2.getId());
       //break;

}


Sequence generator

There are different ways to generate sequence
1) Automatic
2) Custom

1) Automatic
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator= "countryid-gen")
@SequenceGenerator(name = "countryid-gen", sequenceName = "COUNTRY_SEQ",
              allocationSize = 1, initialValue = 0)
@Column(name = "COUNTRY_ID")

private int id;

2) Custom 
First need to create 
a) Custom Class, then 
b) implement that custom class.

a) Custom Class
package com.pristine.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class EmployeeCodeGenerator implements IdentifierGenerator {


    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {

        String prefix = "E";
        Connection connection = session.connection();
        try {

            PreparedStatement ps = connection
                    .prepareStatement("SELECT nextval ('EMPLOYEE_SEQ') as nextval");

            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("nextval");
                String code = prefix + StringUtils.leftPad("" + id,3, '0');
                return code;
            }

        } catch (SQLException e) {
            throw new HibernateException(
                    "Unable to generate Stock Code Sequence");
        }
        return null;
    }
}


b) Implementation of Custom Class
@Id
@GenericGenerator(name="seq_id", strategy="com.pristine.util.EmployeeCodeGenerator")
@GeneratedValue(generator="seq_id")
@Column(name = "ID", nullable = false)
private String id;



Thursday, 11 December 2014

Hibernate Error

Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.List, at table: Country_master, for columns: [org.hibernate.mapping.Column(stateMasters)]

Add
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
</dependency>

=======================================================

Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.OneToMany.orphanRemoval()Z

That may be due to hibernate-jpa-2.0-api.jar

Add Below code
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
   <exclusions>
      <exclusion>
         <groupId>org.hibernate.javax.persistence</groupId>
 <artifactId>hibernate-jpa-2.0-api</artifactId>
      </exclusion>
   </exclusions>
</dependency>


========================================================

Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.pristine.domain.StateMasterEntity


@OneToMany(cascade = CascadeType.ALL)

Sunday, 7 December 2014

onetomany mapping with example



@Entity
@Table(name = "AUTHOR")
public class Author {
       private long id;
       private String name;
       private String email;
      
       public Author() {
       }
                    
       public Author(String name, String email) {
              this.name = name;
              this.email = email;
       }

       @Id
       @Column(name = "AUTHOR_ID")
       @GeneratedValue(strategy=GenerationType.AUTO)
       public long getId() {
              return id;
       }

//setter/getter
}





@Entity
@Table(name = "BOOK")
public class Book {
       private long id;
       private String title;
       private String description;
       private Date publishedDate;
      
       private List<Author> author = new ArrayList<Author>();

       public Book() {
       }

       @Id
       @Column(name = "BOOK_ID")
       @GeneratedValue(strategy=GenerationType.AUTO)
       public long getId() {
              return id;
       }


       @Temporal(TemporalType.DATE)
       @Column(name = "PUBLISHED")
       public Date getPublishedDate() {
              return publishedDate;
       }

       @OneToMany(cascade = CascadeType.ALL)
       @JoinColumn(name = "BOOK_ID")
       public List<Author> getAuthor() {
              return author;
       }

//setter/getter
}






public class BooksTest {

       public static void main(String[] args) {
              SessionFactory sessionFactory = HibernateUtils.getSessionFactory();
              Session session = sessionFactory.openSession();
              try{
                     session.beginTransaction();
                    
                     // creates a Book entity
                     Book newBook = new Book();
                     newBook.setTitle("Pro PHP MVC");
                     newBook.setDescription("Php MVC Book");
                     newBook.setPublishedDate(new Date());
                     List<Author> authors= new ArrayList<Author>();
                     authors.add(new Author("Shambhu Kumar", "shambhu@gmail.com"));
                     authors.add(new Author("Ravi Kumar", "Ravi@gmail.com"));
                     newBook.setAuthor(authors);
                    
                     // persists the book entity
                     Long bookId = (Long) session.save(newBook);
                    
                     // gets the book entity back
                     Book book = (Book) session.get(Book.class, bookId);
                     System.out.println("Book's Title: " + book.getTitle());
                     System.out.println("Book's Description: " + book.getTitle());
                    
                    
                     book.getAuthor().add(new Author("Shambhu1", "shambhu@gmail.com"));
                     book.getAuthor().add(new Author("Ravi1", "Ravi@gmail.com"));
                    
                     session.update(book);
                     List<Author> authorsList = book.getAuthor();
                     for(Author author:authorsList){
                           System.out.println("Name: " + author.getName());
                           System.out.println("Mail: " + author.getEmail());     
                     }
                    
              }
             
              finally{
                     session.getTransaction().commit();
                     session.close();    
                     sessionFactory.close();
              }
             
                    
       }
}




Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP