周末复习

搭建Hibernate环境,连接MySql数据库

  • 创建Maven项目

    • 1.什么是groupid和artifactId?
      groupid和artifactId被统称为“坐标”是为了保证项目唯一性而提出的,如果你要把你项目弄到maven本地仓库去,你想要找到你的项目就必须根据这两个id去查找。
        groupId一般分为多个段,这里我只说两段,第一段为域,第二段为公司名称。域又分为org、com、cn等等许多,其中org为非营利组织,com为商业组织。举个apache公司的tomcat项目例子:这个项目的groupId是org.apache,它的域是org(因为tomcat是非营利项目),公司名称是apache,artigactId是tomcat。
    • 注意:如果选择的时War,pom.xml会报错。
    • 解决方案:在src->webapp下面新建 WEB-INF文件夹,里面粘贴一个web.xml
  • 在pom.xml里面引用hibernate的依赖

    • 百度搜索mvn
    • 搜索hibernate
    • 找带有core的
  • hibernate的运行需要hibernate.cfg.xml

    • 注意名字必须是它,具体里面的配置内容寻找百度

    • 放在src/main/resources下面

    • 里面包含了要连接数据库的基本信息,例如数据库的账号,密码

      重点代码

      Configuration cfg = new Configuration().configure();//会到类路径下读取hibernate.cfg.xml
      SessionFactory fac = cfg.buildSessionFactory();//会启动一个新线程
      Session session = fac.openSession();//打开一个数据库对话,肯定会建立数据库
      session.close();//关闭session
      fac.close();//关闭fac
      

    创建实体类,配置mapping,保存对象

  • 创建实体类

  • 例如创建一个entity包,里面放一个User类

  • 新建一个mapping文件

    • 网上有mapping文件

    • <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
      <!-- mapping文件用来描述Entity与数据表的关系 -->
      <hibernate-mapping>
      	
      	<class name="entity.User" table="rethink_user" >
      		<id name="id" column="rethink_id">
      			<generator class="idntity"></generator>
      		</id>
      		<property name="username" column="rethink_name" type="string" length="16"></property>
      		<property name="password" column="rethink_password"></property>
      		<property name="age"></property>
      	</class>
      
      </hibernate-mapping>
      
      

      对mapping编写完成后需要在hibernate写入映射

        		<mapping resource ="entity/Person.hbm.xml"></mapping>
      
      
  • 接着运行Test.java,可能会出现如下错误

数据库方言Error

 Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
  • 解决数据库方言BUG

  • <!-- 数据库方言配置 org.hibernate.dialect.MySQLDialect (出现问题就更换) -->
           <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
         
    
  • 保存对象

    • 在Test.java里面编写
package demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();// 会到类路径下读取hibernate.cfg.xml
		SessionFactory fac = cfg.buildSessionFactory();// 会开启一个新线程
		Session session =  fac.openSession();//打开一条数据库会话,肯定会建立连接
		System.out.println("成功连接数据库");
		User user = new User();
		user.setAge(18);
		user.setUsername("刘延昊");
		user.setPassword("123456");
		session.save(user);
		session.close();
		fac.close();
	}

}

  • 重点代码

    User user = new User();
    user.setAge(18);
    user.setUsername(“刘延昊”);
    user.setPassword(“123456”);
    session.save(user);

删除对象,事务启动,提交,回滚

删除对象

package test;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestDelete {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		User us = new User();
		us.setId(1);
		session.delete(us);//虽然参数时Object,但实际上用ID
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

  • 注意要启动事务
  • 注意要提交事务

保存50个对象,修改对象

TestSave50.java

package test;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestSave50 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		for(int i = 0;i<50;i++) {
			User user = new User();
			user.setUsername("刘"+i);
			user.setAge(i);
			user.setPassword("123456");
			session.save(user);
		}
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

  • session.save(user);

TestUpdate.java

package test;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestUpdate {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		//根据ID修改密码,先查询-再修改
		User user = session.get(User.class, 3);
		user.setPassword("12");
		session.update(user);
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

Query 与list ----Query与uniqueResult

TestQuery.java

package test;
import java.util.List;

import org.hibernate.Query;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestQuery {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		//HQL语句,纯查询语句,面向对象的语言,在HQL里面没有数据库的概念
		String hql = "from entity.User where age>30";  //也可以加别名
		Query<User> query = session.createQuery(hql);
		List<User> list = query.list();
		for(User us:list) {
			System.out.println(us.getUsername());
		}
		Query<User> query2 = session.createQuery("from entity.User where username='刘3'");
		User un = query2.uniqueResult();//如果查出多个数据,会抛异常
		System.out.println(un.getId());
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

  • String hql = “from entity.User where age>30”; //也可以加别名
    Query query = session.createQuery(hql);
    List list = query.list();
    for(User us:list) {
    System.out.println(us.getUsername());
    }
    Query query2 = session.createQuery(“from entity.User where username=‘刘3’”);
    User un = query2.uniqueResult();//如果查出多个数据,会抛异常
    System.out.println(un.getId());

Hibernate使用UUID主键

Book.java

package entity;

public class Book {
private String id;
private String name;
private String author;
public String getId() {
	return id;
}
public void setId(String id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getAuthor() {
	return author;
}
public void setAuthor(String author) {
	this.author = author;
}
}

Book.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- mapping文件用来描述Entity与数据表的关系 -->
<hibernate-mapping>
	
	<class name="entity.Book" table="rethink_book" >
		<id name="id" column="book_id">
			<generator class="uuid"></generator><!-- 使用Hibernate的UUID主键 -->
		</id>
		<property name="name" column="book_name"></property>
		<property name="author" column="book_author"></property>
	</class>

</hibernate-mapping>

在hibernate.cfg.xml里面配置相关的mapping

TestUUID.java

package test;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.Book;
import entity.User;

public class TestUUID {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		Book book = new Book();
		book.setAuthor("希不");
		book.setName("我的书");
		session.save(book);
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

OpenSession与CurrentSession

  • 首先在hibernate.cfg.xml里面配置

    <!-- 将Session与线程绑定=> 只有配置了该配置,才能使用getCurrentSession -->
         <property name="hibernate.current_session_context_class">thread</property>
    

TestSession.java

package test;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestSession {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		Session session1 = fac.openSession();
		Session session2 = fac.openSession();
		Session session3 = fac.getCurrentSession();//获取最近的currentSession,没有就创建一个,不要以为是Session,和session1和session2没有关系
		Session session4 = fac.getCurrentSession();
		
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

  • OpenSession 打开新的Session
    GetCurrentSession 获取最近的Session,我们需要在配置文件中描述何为最近

GetCurrentSession()会获取最近的CurrentSession,如果没有就建一个,

OpenSession在查询的时候可以不用事务,用过之后必须关闭
CurrentSession必须使用事务,使用之后不用关闭

无论什么Session,无论增删改查,都加事务就肯定没错,

带有参数的HQL语句(问号参数和冒号参数)

TestParams.java

package test;
import org.hibernate.Query;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestParams {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		String hql = "from User u where u.username = ?";
		Query<User> query = session.createQuery(hql);
		query.setParameter(0, "刘1");
		User user = query.uniqueResult();
		System.out.println(user.getId());
		String hql2 = "from User u where u.username =:bieming";
		Query<User> query2 = session.createQuery(hql2);
		query2.setParameter("bieming", "刘2");
		User user2 = query2.uniqueResult();
		System.out.println(user2.getId());
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}

  • String hql = “from User u where u.username = ?”;
  • String hql2 = “from User u where u.username =:bieming”;

投影查询(只查询属性的几个属性)

TestQuery2.java

package test;
import java.util.List;

import org.hibernate.Query;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestQuery2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		//HQL语句,纯查询语句,面向对象的语言,在HQL里面没有数据库的概念
		String hql = "select new User(id,username) from User"; 
		Query<User> query = session.createQuery(hql);
		List<User> list = query.getResultList();
		for(User user:list) {
			System.out.println(user.getId());
			System.out.println(user.getUsername());
			System.out.println(user.getAge());
			System.out.println(user.getPassword());
			System.out.println("-----------");
		}
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}


  • String hql = “select new User(id,username) from User”;
    Query query = session.createQuery(hql);

HQL得到数据数组

package test;
import java.util.List;

import org.hibernate.Query;
//删除对象
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.User;

public class TestQuery3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory fac = cfg.buildSessionFactory();
		Session session = fac.openSession();
		session.getTransaction().begin();//启动事务
		//HQL语句,纯查询语句,面向对象的语言,在HQL里面没有数据库的概念
		String hql = "select username,age from User"; 
		Query<Object> query = session.createQuery(hql);
		List<Object> list = query.getResultList();
		for(Object obj:list) {
			Object[] arr = (Object[])obj;
			String name = (String)arr[0];
			int age = (Integer) arr[1];
			System.out.println(name);
			System.out.println(age);
			System.out.println("------------");
		}
		session.getTransaction().commit();//提交事务
		session.close();
		fac.close();
	}

}


  • String hql = “select username,age from User”;
上一篇:TopCoder 14084 BearPermutations2【笛卡尔树+dp】


下一篇:[SDOI2019]移动金币(博弈论+阶梯Nim+按位DP)