package com.wyx.hibernate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import org.hibernate.Session;
import com.wyx.hibernate.utils.HibernateUtils;
public class InitData {
public static void main(String[] args) {
addStudent();
addwuye();
}
public static void addStudent(){
for(int i = 1; i <= 10; i++){
Group group = new Group();
group.setName(" "+i);
for(int j = 1; j<= 10; j++){
User user = new User();
//
user.setCreateTime(randomDate("2008-8-8","2011-3-28"));
user.setName(" "+i+" " + j );
user.setGroup(group);
Session session = HibernateUtils.getSession();
session.beginTransaction();
try {
session.save(user);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
}
}
public static void addwuye(){
for(int i = 1; i <= 10; i++){
User user = new User();
user.setCreateTime(new Date());
user.setName(" "+i);
Session session = HibernateUtils.getSession();
session.beginTransaction();
try {
session.save(user);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally{
HibernateUtils.closeSession(session);
}
}
}
//
private static Date randomDate(String beginDate, String endDate) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date start = format.parse(beginDate);//
Date end = format.parse(endDate);//
// getTime() 1970 1 1 00:00:00 GMT Date 。
if (start.getTime() >= end.getTime()) {
return null;
}
long date = random(start.getTime(), end.getTime());
return new Date(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static long random(long begin, long end) {
long rtn = begin + (long) (Math.random() * (end - begin));
// ,
if (rtn == begin || rtn == end) {
return random(begin, end);
}
return rtn;
}
}