zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java_hibernate

2023-09-11 14:21:36 时间
  1. 入门http://jingyan.baidu.com/article/cbf0e500965a352eab289368.html
  2. 步骤
    1、查看是否hibernate支持:file-->plugins-->hibernate(搜索)
    2、新增web project,勾选web application、hibernate、create default hibernate
    3、点击左下角框框,弹出database,读取sqlserver数据库数据自动生成配置文件
    4、编写测试程序实现插入数据操作
    public class HTest {
        public static void main(String[] args) {
            TableName log = new TableName();
    //        log.setId(10001);
            log.setAid(1);
            log.setRelatedId("111");
    
            try {
                String remark="111的备注";
                String ret = new String(remark.getBytes("ISO-8859-1"),"GB2312");
                log.setRemark(ret);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String dateStr = sdf.format(date);
            log.setCreated(Timestamp.valueOf(dateStr));
    
           SessionFactory fac=  new AnnotationConfiguration().configure().buildSessionFactory();
    
    //        Configuration configuration = new Configuration();
    //        SessionFactory fac = configuration.configure().buildSessionFactory();
    
            Session session =fac.getCurrentSession();
            session.beginTransaction();
            session.save(log);
            session.getTransaction().commit();
        }

     

  3. 过程中遇到的问题及解决方案
      1、 Could not load requested class : com.microsoft.sqlserver.jdbc.SQLServerDriver
   解决方法:缺少sqlserver驱动导致
    1、下载sqljdbc4.jar 
    2、file-->project structure-->modules-->dependencies-->引入sqljdbc4.jar
 
   2、No CurrentSessionContext configured 
          解决方法:hibernate.cfg.xml配置文件中加上节点:<property name="current_session_context_class">thread</property>
 
    3、当 IDENTITY_INSERT 设置为 OFF 时,不能为表 '' 中的标识列插入显式值
  解决方法:sqlserver中主键为自增长导致,数据库对应的实体类加上:
  @GeneratedValue(strategy = GenerationType.IDENTITY)
 
   4、hibernate写入数据库时出现乱码
          解决方法:暂未找到解决方法