minor cleanup work - formatting

This commit is contained in:
eugenp 2017-02-04 14:14:23 +02:00
parent 4d5624161f
commit bd6fe7269e
5 changed files with 221 additions and 208 deletions

View File

@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory();
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}

View File

@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items;
public class HibernateOneToManyAnnotationMain {
public static void main(String[] args) {
public static void main(String[] args) {
Cart cart = new Cart();
cart.setName("MyCart");
Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2);
cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try{
//Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
//start transaction
tx = session.beginTransaction();
//Save the Model object
session.save(cart);
session.save(item1);
session.save(item2);
//Commit transaction
tx.commit();
System.out.println("Cart ID="+cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
}catch(Exception e){
System.out.println("Exception occured. "+e.getMessage());
e.printStackTrace();
}finally{
if(!sessionFactory.isClosed()){
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
Cart cart = new Cart();
cart.setName("MyCart");
Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
cart.setTotal(10 * 1 + 20 * 2);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
// Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
// start transaction
tx = session.beginTransaction();
// Save the Model object
session.save(cart);
session.save(item1);
session.save(item2);
// Commit transaction
tx.commit();
System.out.println("Cart ID=" + cart.getId());
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
} catch (Exception e) {
System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace();
} finally {
if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory");
sessionFactory.close();
}
}
}
}

View File

@ -11,46 +11,53 @@ import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="CART")
@Table(name = "CART")
public class Cart {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="cart_id")
private long id;
@Column(name="total")
private double total;
@Column(name="name")
private String name;
@OneToMany(mappedBy="cart")
private Set<Items> items;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cart_id")
private long id;
@Column(name = "total")
private double total;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "cart")
private Set<Items> items;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}

View File

@ -10,65 +10,76 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="ITEMS")
@Table(name = "ITEMS")
public class Items {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="item_id")
private String itemId;
@Column(name="item_total")
private double itemTotal;
@Column(name="quantity")
private int quantity;
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart cart;
//Hibernate requires no-args constructor
public Items(){}
public Items(String itemId, double total, int qty, Cart c){
this.itemId=itemId;
this.itemTotal=total;
this.quantity=qty;
this.cart=c;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public double getItemTotal() {
return itemTotal;
}
public void setItemTotal(double itemTotal) {
this.itemTotal = itemTotal;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "item_id")
private String itemId;
@Column(name = "item_total")
private double itemTotal;
@Column(name = "quantity")
private int quantity;
@ManyToOne
@JoinColumn(name = "cart_id", nullable = false)
private Cart cart;
// Hibernate requires no-args constructor
public Items() {
}
public Items(String itemId, double total, int qty, Cart c) {
this.itemId = itemId;
this.itemTotal = total;
this.quantity = qty;
this.cart = c;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public double getItemTotal() {
return itemTotal;
}
public void setItemTotal(double itemTotal) {
this.itemTotal = itemTotal;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.oneToMany.main;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Items;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.Matchers.hasSize;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@ -17,51 +17,47 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Items;
//@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateOneToManyAnnotationMainTest {
private static SessionFactory sessionFactory;
private Session session;
public HibernateOneToManyAnnotationMainTest() {
}
@BeforeClass
public static void beforeTests() {
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName())
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()).setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa")
.setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
session.beginTransaction();
}
@Test
public void givenSession_checkIfDatabaseIsEmpty(){
public void givenSession_checkIfDatabaseIsEmpty() {
Cart cart = (Cart) session.get(Cart.class, new Long(1));
assertNull(cart);
}
@Test
public void testAddItemsToCart() {
Cart cart = new Cart();
Set <Items> cartItems = new HashSet<>();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items("I10", 10, 1, cart);
@ -70,33 +66,32 @@ public class HibernateOneToManyAnnotationMainTest {
cart.setItems(itemsSet);
assertNotNull(cart);
System.out.println("Items added to cart");
}
@Test
public void givenSession_checkIfDatabaseIsPopulated_afterCommit(){
Cart cart = new Cart();
Set <Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setItemId("I10");
item1.setItemTotal(10);
item1.setQuantity(1);
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
cart = (Cart) session.get(Cart.class, new Long(1));
assertNotNull(cart);
session.close();
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setItemId("I10");
item1.setItemTotal(10);
item1.setQuantity(1);
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
cart = (Cart) session.get(Cart.class, new Long(1));
assertNotNull(cart);
session.close();
}
}