今天在使用hibernate的时候,插入mysql的数据中的中文总是显示乱码,之前出现过类似的问题,但是没有太在意,今天又发生了。所以向彻底的解决一下。

参考的博文: http://www.cnblogs.com/amboyna/archive/2008/06/18/1224570.html

 

我的实体类:

package com.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity; /*JPA注解*/
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;


/**
 * 学生实体类
 * @author Administrator
 *
 */
//@Entity(name="t_students")
@Entity//表示这是一个实体类
@Table(name="t_students",schema="bookshop")//修改数据库中映射的表名
//schema:表示数据库的名称
//name:表示数据库的表名
//Embedddable注解表示一个非Entity类,但是可以嵌入到另外一个实体类中作为属性而存在
public class Students implements Serializable{

    //private int sid;  //学号
    private String sid;  //将学号改成字符串类型
    private String sname; //姓名
    private String gender; //性别
    private Date birthday;//出生日期
    private String major;//专业
    //private String address; //地址
    private Address add;//地址
    
    
    public Address getAdd() {
        return add;
    }

    public void setAdd(Address add) {
        this.add = add;
    }

    public Students()
    {
        
    }

    public Students(String sid, String sname, String gender, Date birthday,
            String major,Address add) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.major = major;
        //this.address = address;
        this.add = add;
    }

    @Id
    //@GeneratedValue //默认生成策略为自动增长
    //@GeneratedValue(strategy=GenerationType.AUTO)//手动设置自动增长(但是将主
    //键字段改成字符串类型之后不可以实现子哦的那个增自动增长了,这时候可以实现的后宫复制)
    //@GeneratedValue(strategy=GenerationType.IDENTITY)//
    @GeneratedValue(generator="sid")
    @GenericGenerator(name="sid",strategy="assigned")//主键手工赋值
    @Column(length=20)//但是还是没有生成数据库表,因此,字符串为主键时不可以指定主键的生成策略为AUTO_increment
    //
    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    //@Id
    //@Column(length=20)
    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }    

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    
    
}

 

 

以下是我的hibernate.cfg.xml的配置情况:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!-- old: http://hibernate.sourceforge.net/hibernate-configuration-3.6.dtd -->
<!-- new: http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd -->
<!--    : http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd -->
<hibernate-configuration>
<session-factory>
    <!-- 显示sql语句 -->
    <property name="show_sql">true</property>
    <property name="myeclipse.connection.profile">bookshop</property>
    <!-- <property name="connection.url">
        jdbc:mysql://localhost:3306/bookshop
        jdbc:mysql://localhost:3306/database?useUnicode=true&amp;characterEncoding=UTF-8 
    </property> -->
    
    <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
    <property name="connection.username">root</property>
    <property name="connection.password">xxxxxxxxcc</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    <property name="hibernate.current_session_context_class">thread</property>
    
    <!-- 将实体类映射到数据库 -->
    <mapping class="com.entity.Students"/>
</session-factory>
</hibernate-configuration>

 

之后生成数据库表结构:

    @Test
    public void testShemaExport(){
        //创建Hibernate配置对象
        Configuration configuration = new Configuration().configure();
        
        //创建服务注册对象
        ServiceRegistry serviceRegistry = 
                new ServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .buildServiceRegistry();
        
        //创建sessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        
        //生成SchemaExport对象
        SchemaExport export = new SchemaExport(configuration);
        //调用schemaExport的create生成数据库表结构
        export.create(true, true);    
    }
    

 

将数据插入数据库:

@Test
    public void addStudents()
    {
        //创建Hibernate配置对象
        Configuration configuration = new Configuration().configure();
        
        //创建服务注册对象
        ServiceRegistry serviceRegistry = 
                new ServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .buildServiceRegistry();
        
        //创建sessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        //创建会话
        Session session = sessionFactory.getCurrentSession();
        //创建事务
        Transaction tx = session.beginTransaction();
        
        //创建一个地址对象
        Address add = new Address("700005","武当山","1388732789");
        //创建一个学生对象
        Students s = new Students("S00000001","张三丰","男", new Date(),"太极拳",add);
        //保存session
        session.save(s);//在没有执行commit之前数据库里面是没有保存数据的
        tx.commit();
    }

 

log:

2016-4-16 14:46:47 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
2016-4-16 14:46:47 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.21.Final}
2016-4-16 14:46:47 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
2016-4-16 14:46:47 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
2016-4-16 14:46:47 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
2016-4-16 14:46:47 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
2016-4-16 14:46:47 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2016-4-16 14:46:47 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
2016-4-16 14:46:48 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
2016-4-16 14:46:48 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
2016-4-16 14:46:48 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
2016-4-16 14:46:48 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
2016-4-16 14:46:48 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-4-16 14:46:48 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2016-4-16 14:46:48 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
2016-4-16 14:46:48 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: t_students
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: t_students
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: t_students
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table bookshop.t_students (sid varchar(20) not null, address varchar(255), phone varchar(255), postCode varchar(255), birthday datetime, gender varchar(255), major varchar(255), sname varchar(255), primary key (sid))
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 't_students' already exists
2016-4-16 14:46:49 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: 
    insert 
    into
        bookshop.t_students
        (address, phone, postCode, birthday, gender, major, sname, sid) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)

 

 

数据库显示正常。中文乱码问题彻底小时。