SSH:hiberate实现数据的查询(单查询和全查询)

先配置一大堆文件

1,User.java-对象类

package Test;

import java.util.Date;

public class User {
	private Integer id;
	private String name;
	private String password;
	private Integer age;
	private String gender;
	private Date birthday;
	

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	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 int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + this.id;
		return result;
	}
}

2,配置hiberate.cfg.xml


 

 

   

     com.mysql.cj.jdbc.Driver

     jdbc:mysql://127.0.0.1:3306/Hibernatedatabase3?serverTimezone=GMT

     root

     123456

     org.hibernate.dialect.MySQLDialect
	 
	 update
     
      
   

 

3,配置User.hub.xml




	
		
			
		
		
			
		
		
			
		
		
			
		
		
			
		
		
			
		
	

操作类---核心

注释为根据主键查询,非注释为查询全表信息

package Test;

import java.util.Date;
import java.util.List;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;

public class UserTest {
	public static void main(String[] args) {
		SessionFactory sf = null; // 负责Session的实现和建立
		Session session = null; // Session与数据库之间的一个会话,是核心
		Configuration cfg = new Configuration().configure();// 主要负责加载和管理Hiberate的配置信息,也可加载映射文件信息
		sf = cfg.buildSessionFactory();
		session = sf.openSession();
//		User user = (User) session.get(User.class, 1);//查询主键id=1的用户
//		System.out.println(user.getName() + " " + user.getPassword() + " " + user.getGender());
		String hql = "from User";
		List userList = session.createQuery(hql).list();
		for (User user : userList) {
			System.out.println(user.getName() + " " + user.getPassword() + " " + user.getGender());
		}
	}
}

 

你可能感兴趣的:(SSH)