无意中发现了123.06的一个txt格式的数据文件...,又联想到这几天正在学习javaEE中的hibernate框架,于是就应用了一下,准备练练手
仔细分析后这个文件是类似这种格式
****@qq.com----683***----郑**----3**221987***0011----z6***605----1506**4----*****266@qq.com
每一行都是一条记录,首先想到的是应该先对txt文件进行读取,然后对每一行的数据进行封装,最后在进行hibernate的数据持久化操作****@qq.com----683***----郑**----3**221987***0011----z6***605----1506**4----*****266@qq.com
步骤:
1.先创建一个java工程
2.导入所必须的jar包 hibernate + mysql
3.编写实体类(持久化类) User.java
4.编写实体映射文件(持久化映射文件)User.hbm.xml
5.编写主映射文件hibernate.cfg.xml
6.编写hibernateUtils工具类
7.测试
详细代码
User.java
package bean; public class User { private int id; private String id_card;//身份证号 private String username;//用户名 private String password;//密码 private String realname;//真实姓名 private String email;//邮箱 private String phone;//电话 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getId_card() { return id_card; } public void setId_card(String id_card) { this.id_card = id_card; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "User [id=" + id + ", email=" + email + ", username=" + username + ", realname=" + realname + ", id_card=" + id_card + ", password=" + password + ", phone=" + phone + "]"; } }
User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="bean.User" table="user"> <id name="id" column="id"> <generator class="native"/> </id> <property name="id_card" column = "id_card"/> <property name="username" column = "username"/> <property name="password" column = "password"/> <property name="realname" column = "realname"/> <property name="email" column = "email"/> <property name="phone" column = "phone"/> </class> </hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.username">root</property><!-- 数据库用户名 --> <property name="connection.password">root</property> <!-- 数据库密码 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- ?useUnicode=true&characterEncoding=UTF-8 --> <property name="connection.url">jdbc:mysql:///test</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">false</property><!-- 显示生成sql语句 --> <property name="hbm2ddl.auto">update</property><!-- 会先删除表在创建 可选update --> <mapping resource="bean/User.hbm.xml"/> </session-factory> </hibernate-configuration>
HibernateUtil.java
JunitTest.javapackage util; import java.io.Serializable; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; @SuppressWarnings("deprecation") public class HibernateUtil { private static SessionFactory sf; static{ Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); sf = cfg.buildSessionFactory(); } public static Session getSession(){ return sf.openSession(); } public static void add(Object entity){ Session session = null; Transaction tx = null; session = HibernateUtil.getSession(); tx = session.beginTransaction(); session.save(entity); tx.commit(); session.close(); } public static void delete(Object entity){ Session session = null; Transaction tx = null; session = HibernateUtil.getSession(); tx = session.beginTransaction(); session.delete(entity); tx.commit(); session.close(); } public static void update(Object entity){ Session session = null; Transaction tx = null; session = HibernateUtil.getSession(); tx = session.beginTransaction(); session.update(entity); tx.commit(); session.close(); } @SuppressWarnings("rawtypes") public static Object findById(Class clazz,Serializable id){ Session session = null; session = HibernateUtil.getSession(); Object ob = session.get(clazz, id); session.close(); return ob; } public static Object findByName(String name){ Session session = null; session = HibernateUtil.getSession(); Query query = session.createQuery("select * from login where name='"+name+"'"); query.setParameter("name", name); Object ob = query.uniqueResult(); session.close(); return ob; } }
package test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import org.junit.Test; import util.HibernateUtil; import bean.User; public class JunitTest { @Test public void test() { //HibernateUtil hu = new HibernateUtil(); String filePath = "E:\\12306.txt"; readTxtFile(filePath); } /** * 功能:Java读取txt文件的内容 * 步骤:1:先获得文件句柄 * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取 * 3:读取到输入流后,需要读取生成字节流 * 4:一行一行的输出。readline()。 * 备注:需要考虑的是异常情况 * @param filePath */ @SuppressWarnings("static-access") public static void readTxtFile(String filePath){ HibernateUtil hu = new HibernateUtil(); User user=null; try { String encoding="UTF-8"; //String encoding="GBK"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ String[] StrArray = lineTxt.split("----"); //user = new User(id, email, username, realname, id_card, password, phone) user = new User(); user.setEmail(StrArray[0]); user.setUsername(StrArray[1]); user.setRealname(StrArray[2]); user.setId_card(StrArray[3]); user.setPassword(StrArray[4]); user.setPhone(StrArray[5]); hu.add(user); } read.close(); }else{ System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } System.out.println("end!"); } }
ps: 数据插入时不知道怎么回事,中文总是乱码,大约弄了一个多小时,多处查阅资料后才发现原来自己的数据库用的是配合phpstudy的自带的,里边的参数与我的插入编码格式不对应。记录一下
1、首先需要修改MySQL数据库的配置文件mysql.ini。 default-character-set属性有两个,一个在[mysql]下面,另外一个在[mysqld]下面。
2、同时创建hibernate数据库时需要显示设置数据库的编码方式为utf8。示例:[mysql] default-character-set=utf8 [mysqld] character-set-server=utf8
3、做完这两步还是不行,需要修改hibernate的配置文件hibernate.cfg.xml,在配置文件配置hibernate.connection.url属性。示例:create database daycode default charset=utf8;
<property name="connection.url">jdbc:mysql:///test?useUnicode=true&characterEncoding=UTF-8</property>