package helloworld; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Message { @Id @GeneratedValue private Long id; private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }
package helloworld; import static org.junit.Assert.assertEquals; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataBuilder; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.service.ServiceRegistry; import org.junit.Test; public class HelloWorldHibernate { @Test public void testHelloWorld() { /* * SessionFactory sessionFactory = new MetadataSources( new * StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build()) * .buildMetadata().buildSessionFactory(); */ StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); serviceRegistryBuilder //.applySetting("hibernate.connection.datasource", "books") .applySetting("hibernate.connection.url", "jdbc:mysql://localhost:3306/test") .applySetting("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .applySetting("hibernate.connection.user", "root") .applySetting("hibernate.connection.password", "****") .applySetting("hibernate.format_sql", "true") .applySetting("hibernate.use_sql_comments", "true") .applySetting("hibernate.hbm2ddl.auto", "create-drop"); ServiceRegistry serviceRegistry = serviceRegistryBuilder.build(); // The MetadataSources API has many methods for adding mapping sources; MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(helloworld.Message.class); MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(); Metadata metadata = metadataBuilder.build(); assertEquals(metadata.getEntityBindings().size(), 1); SessionFactory sessionFactory = metadata.buildSessionFactory(); // Whenever you call getCurrentSession() in the same thread, you get the // same org.hibernate.Session Session session = sessionFactory.openSession(); session.beginTransaction(); Message message = new Message(); message.setText("Hello World!"); session.persist(message); session.getTransaction().commit(); session.close(); session = sessionFactory.openSession(); session.beginTransaction(); List<Message> messages = session.createCriteria(Message.class).list(); // SELECT * from MESSAGE assertEquals(messages.size(), 1); assertEquals(messages.get(0).getText(), "Hello World!"); session.getTransaction().commit(); session.close(); } }