Java • Mapping Java classess to databatase tables • Free software • Mapping is done by using • 1) XML configuration or • 2) Java annotations • Classes must have no-argument constructor • Collections are stored in Set or List, also generics are supported • Can be used part of Java SE or EE
2. Take the jars from the required/ folder and put those to classpath 3. Create plain old java object (Employee.java) 4. Create Java file with main – method that stores POJOs to database (StoreData.java) 5. Optional: Create hibernate mapping xml file that has rules how to map POJO to relational database (employee.hbm.xml) 6. Create hibernate configuration xml file that defines the database you are accessing (hibernate.cfg.xml) Notice also MySQL Driver. Separate download.
public static void main(String[] args) { // Create configuration object Configuration cfg = new Configuration(); // Populate the data of the default configuration file which name // is hibernate.cfg.xml cfg.configure(); // Create SessionFactory that can be used to open a session SessionFactory factory = cfg.buildSessionFactory(); // Session is an interface between Java app and Database // Session is used to create, read, delete operations Session session = factory.openSession(); Transaction tx = session.beginTransaction(); // Create pojo Employee e1 = new Employee(); e1.setId(2); e1.setFirstName("Hello"); e1.setLastName("World"); // Save to database session.persist(e1); tx.commit(); // Close connection factory.close(); } }
DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="employees"> <id name="id"> <generator class="assigned"></generator> </id> <property name="firstName"></property> <property name="lastName"></property> </class> </hibernate-mapping> assigned => id is assigned in code Change to identity so that mysql will handle autoincrement. Lot of possibilities here: http://www.javatpoint. com/generator-classes
List<Employee> results = session.createQuery("FROM Employee").list(); • SELECT • List<String> results = session.createQuery("SELECT firstName FROM Employee").list(); • WHERE • List<Employee> results = session.createQuery("FROM Employee WHERE ID = 10").list(); • You will get a warning: [unchecked] unchecked conversion because hibernate is not type safe by design. Solution: • @SuppressWarnings("unchecked")
Each pojo will have a primary key which you annotate // by using @Id @Id @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName;
Each pojo will have a primary key which you annotate // by using @Id @Id // Define strategy how to save this to db // IDENTIFY allow auto increment on demand in MySQL @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "firstname") private String firstName; @Column(name = "lastname") private String lastName;