package com.yagapps.example9;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
/*Remember here the Query from Boy must have the same as Entity class ,Boy*/
@NamedQueries( {@NamedQuery(name="findBoy" ,query="from Boy")} )
@Entity
public class Boy {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
This class is Entity class
and now below the TestClient
package com.yagapps.example9;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class TestClient {
/**
* @param args
*/
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Boy.class);
config.configure();
new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Boy b = new Boy();
b.setId("A201");
b.setName("ramesh");
session.save(b);
session.getTransaction().commit();
session.beginTransaction();
Query query = session.getNamedQuery("findBoy");
List<Boy> l = query.list();
for(Boy b1 : l)
System.out.println(b1.getId());
session.getTransaction().commit();
}
}
No comments:
Post a Comment