package com.finshope.test;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import com.finshope.entity.City;
import com.finshope.util.HbnUtil;
public class TestCity {
Session session;
@Before
public void init() {
session = HbnUtil.getSession();
}
@Test
public void testInsert() {
try {
System.out.println("before");
session.beginTransaction();
session.save(new City(0, "绵阳", null));
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
@Test
public void testGet() {
try {
session.beginTransaction();
City city = session.get(City.class, 7);
System.out.println(city);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
@Test
public void testLoad() {
try {
session.beginTransaction();
//org.hibernate.ObjectNotFoundException
City city = session.load(City.class, 7);
System.out.println(city);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
@Test
public void testDelete() {
try {
session.beginTransaction();
City city = session.get(City.class, 3);
System.out.println(city);
if(city != null) {
session.delete(city);
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
@Test
public void testUpdate() {
try {
session.beginTransaction();
City city = session.get(City.class, 4);
city.setCname("自贡");
city.setCid(2);
System.out.println(city);
if(city != null) {
session.update(city);
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
@Test
public void testOpenSession() {
try {
SessionFactory factory = HbnUtil.getFactory();
System.out.println(factory.openSession());
System.out.println(factory.openSession());
Session session = factory.openSession();
System.out.println(session.get(City.class, 4));
System.out.println(session.get(City.class, 5));
}catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void testCurrentSession() {
try {
SessionFactory factory = HbnUtil.getFactory();
System.out.println(factory.getCurrentSession());
System.out.println(factory.getCurrentSession());
}catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void testFinal() {
final Map<String, Object> map = new HashMap<>();
map.put("a", 1);
System.out.println(map);
}
//C U D
@Test
public void testExecutionOrder() {
try {
session.beginTransaction();
City city = new City();
city.setCid(2);
session.delete(city);
city = new City(5, "yibing", null);
city.setCname("yibing");
session.update(city);
city = new City(10, "cd", null);
session.save(city);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
}