2012-05-10 3 views
1

я пытаюсь некоторые примеры из Java Начиная EE6 с GlassFish3 .so, я создал класс сущностей, который в основном выглядит следующим образом ...Confused с Потоком конструкторами

@Entity 
@Table(name="Book") 
public class Book implements Serializable 
{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 
    @Column(nullable=false) 
    private String name; 
    @Column(nullable=false) 
    private String isbn; 
    private String description; 

    public Book() 
    { 
     // Empty constructor to facilitate construction. 
     System.out.println("The variables have not been initialized...Please initialize them using the Setters or use the provided constructor"); 
    } 

    public Book(String name, String isbn, String description) { 
     this.name = name; 
     this.isbn = isbn; 
     this.description = description; 
    } 

    public String getIsbn() { 
     return isbn; 
    } 

    public void setIsbn(String isbn) { 
     this.isbn = isbn; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 


    @Override 
    public String toString() { 
     return this.name + " - " + this.isbn; 
    } 

    @PrePersist 
    public void printPrePersist(){ 
     System.out.println("Persisting the book "+this.name); 
    } 
    @PostPersist 
    public void printPostPersist(){ 
     System.out.println("Persisted the book "+this.name); 
    } 

} 

и я попытался его упорствовать как это ...

public class MainClass 
{ 
    public static void main(String[] args){ 
     Book book = new Book("Effective Java","ISBN - 1234415","A very good book on Java"); 
     Book book2 = new Book("Learning Java EE","ISBN - 1233415","A good book for Java EE beginners"); 

     // These are the necessary classes 
     EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceAppPU"); 
     EntityManager em = emf.createEntityManager(); 

     // Persist the book here 
     EntityTransaction etx = em.getTransaction(); 
     etx.begin(); 
     em.persist(book); 
     em.persist(book2); 
     etx.commit(); 

     em.close(); 
     emf.close(); 

     System.out.println("The two books have been persisted"); 
    } 
} 

Она сохраняется, но когда я бегу, я вижу выход, как ...

The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
Persisting the book Effective Java 
The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
Persisting the book Learning Java EE 
Persisted the book Learning Java EE 
Persisted the book Effective Java 
The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
The variables have not been initialized...Please initialize them using the Setters or use the provided constructor 
[EL Info]: 2012-05-10 12:01:19.623--ServerSession(17395905)--file:/C:/Users/raviteja.s/Documents/NetBeansProjects/PersistenceApp/src/_PersistenceAppPU logout successful 
The two books have been persisted 

I не понимаю, почему существует так много вызовов конструктора по умолчанию, когда нет одного, сделанного мной ...?

Может ли кто-нибудь объяснить мне, как поток находится в образце, который у меня есть?

+0

Кажется, что EntityManager создает новые объекты книги с помощью конструктора по умолчанию. Если вы выбрали исключение в конструкторе по умолчанию, вы можете увидеть весь стек, который вызывает конструктор (или использовать отладчик), просто добавьте try {throw new Exception(); } catch (Exception e) {e.printStackTrace();} К вашему конструктору и снова запустите его – outofBounds

+1

@outofBounds Или вы можете просто использовать статический 'Thread.dumpStack()' – yshavit

+0

@yshavit thx did'n знаете это. его мутанга проще и чище – outofBounds

ответ

1

JPA использует конструктор без аргументов, чтобы создать экземпляр объектов, а затем привязать поля к этим объектам соответствующим сопоставленным таблицам и столбцам.

Вывод, который вы видите, - это вызовы, которые JPA делает для вас каждый раз, когда он манипулирует вашими сущностями.

+0

Можете ли вы объяснить, почему в конце всего 4 отпечатка, а не 6 или 8 .. есть 3 поля и один идентификатор. Не могли бы вы уточнить, в каких точках задействованы конструкторы. – Flash

+0

Прошу прощения, но я точно не помню поток, используемый в JPA :), если вам интересно, вы должны использовать 'Thread.dumpStack()', как это было предложено yshavit. Но обратите внимание, что отпечатки используются в конструкторе, а не в getters/seters полей ... Так как есть 2 Книги, я могу подумать, что конструктор каждого объекта дважды вызывается JPA. – javatutorial

Смежные вопросы