Java工作笔记-使用Hibernate连接mysql数据库并进行增、删、改、查!

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/84959614

目录

 

环境要求

增加数据库记录

查询数据

修改数据库记录

删除数据库记录


 

环境要求

导入好Hibernate相关jar包,

并且对每一个表都生成了POJO类!

增加数据库记录

表结构如下:

这里使用Hibernate生成的POJO类如下:

Student.java

package my.db;

import java.util.Date;

/**
 * Student entity. @author MyEclipse Persistence Tools
 */

public class Student implements java.io.Serializable {

	// Fields

	private Integer id;
	private String name;
	private String phone;
	private Date birthday;

	// Constructors

	/** default constructor */
	public Student() {
	}

	/** full constructor */
	public Student(Integer id, String name, String phone, Date birthday) {
		this.id = id;
		this.name = name;
		this.phone = phone;
		this.birthday = birthday;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

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

	public String getName() {
		return this.name;
	}

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

	public String getPhone() {
		return this.phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Date getBirthday() {
		return this.birthday;
	}

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

}

Example.java

package my.db;

/**
 * Example entity. @author MyEclipse Persistence Tools
 */

public class Example implements java.io.Serializable {

	// Fields

	private Long id;
	private String author;
	private String title;

	// Constructors

	/** default constructor */
	public Example() {
	}

	/** full constructor */
	public Example(String author, String title) {
		this.author = author;
		this.title = title;
	}

	// Property accessors

	public Long getId() {
		return this.id;
	}

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

	public String getAuthor() {
		return this.author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}

关键的添加数据如下:

Test.java

package my.db;

import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Session dbss = null;
		try
		{
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
			Student row = new Student();
			row.setId(201602);
			row.setName("小明");
			row.setPhone("18888888888");
			row.setBirthday(sdf.parse("1888-8-8"));
			
			Example re = new Example();
			re.setAuthor("小明");
			re.setTitle("装逼指南");
			
			/*连接数据库*/
			dbss = HibernateSessionFactory.getSession();
			Transaction dbtr = dbss.beginTransaction();
			dbss.save(row);
			dbss.save(re);
			dbtr.commit();
			
			System.out.println("数据库生成的小明的ID " + re.getId());
			System.out.println("测试成功!");
		}
		catch(Exception e)
		{
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			if(dbss!= null) dbss.close();
		}

	}

}

运行截图如下:

表内容如下:

查询数据

查询数据有3种分别是:

test1:按主键查询

test2:HQL查询 (Hibernate Query Language)

test3:Native SQL 查询

源码如下:

package my.db;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

	public static void test1(){
		
		Session dbss = null;
		
		try{
			
			//连接数据库
			dbss = HibernateSessionFactory.getSession();
			Integer rowid = new Integer(201602);
			Student row = (Student)dbss.get(Student.class, rowid);
			
			if(row == null){
				System.out.println("找不到记录!");
			}
			else{
				System.out.println("姓名:" + row.getName() + ",电话:" + row.getPhone());
			}
			
		}
		catch(Exception e){
			
			System.out.println("出错:" + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test2(){
		
		Session dbss = null;
		
		try{
			
			//连接数据库
			dbss = HibernateSessionFactory.getSession();
			
			String hql = "from my.db.Student where id > 201601";
			List<Student> results = dbss.createQuery(hql).list();
			
			if(results.size() == 0){
				
				System.out.println("找不到记录!");
			}
			else{
				
				for(Student row: results){
					
					System.out.println("姓名:" + row.getName() + ",电话:" + row.getPhone());
				}
			}
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test3(){
		
		Session dbss = null;
		
		try{
			
			dbss = HibernateSessionFactory.getSession();
			
			String sql = "SELECT * FROM testwebdb.student";
			List<Object[]> results = dbss.createSQLQuery(sql).list();
			
			for(Object[] row : results){
				
				Integer id = Integer.valueOf( row[0].toString() );
				String  name = row[1].toString();
				String  phone = row[2].toString();
				String  brithday = row[3].toString(); // 
				System.out.println("学号" + id + "姓名:" + name + ",电话:" + phone + ",生日" + brithday);
			}
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if (dbss != null)
				dbss.close();
		}
	}
	
	public static void main(String[] args) {
		
		//test1();
		//test2();
		//test3();
	}

}

修改数据库记录

修改数据有3种分别是:

test1:按主键查询

test2:HQL查询 (Hibernate Query Language)

test3:Native SQL 查询

源码如下:

package my.db;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
	
	public static void test1(){
		
		Session dbss = null;
		try{
			
			dbss = HibernateSessionFactory.getSession();
			
			Integer rowid = new Integer(201602);
			Student row = (Student)dbss.get(Student.class, rowid);
			if(row != null){
				
				row.setPhone("16666666666");
				
				//保存到数据
				Transaction dbtr = dbss.beginTransaction();
				dbss.update(row);
				dbtr.commit();
			}
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test2(){
		
		Session dbss = null;
		try{
			
			dbss = HibernateSessionFactory.getSession();
			
			Transaction dbtr = dbss.beginTransaction();
			String hql = "UPDATE Student SET phone='12233330000' WHERE id='201602'";
			int rowsAffected = dbss.createQuery(hql).executeUpdate();
			System.out.print(rowsAffected + " rows affected.");
			dbtr.commit();
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test3(){
		
		Session dbss = null;
		try{
			
			/* 连接数据库 */
			dbss = HibernateSessionFactory.getSession();
			
			// 构造一个普通的SQL语句
			Transaction dbtr = dbss.beginTransaction();
			
			String sql = "UPDATE student SET `phone`='13355550000' WHERE id='201601' ";
			int rowsAffected = dbss.createSQLQuery(sql).executeUpdate();			
			System.out.println(rowsAffected + " rows affected.");
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void main(String[] args) {
		
		//test1();
		//test2();
		test3();
	}

}

 

删除数据库记录

删除数据有3种分别是:

test1:按主键查询

test2:HQL查询 (Hibernate Query Language)

test3:Native SQL 查询

源码如下:

package my.db;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
	
	public static void test1(){
		
		Session dbss = null;
		try{
			
			dbss = HibernateSessionFactory.getSession();
			
			Integer rowid = new Integer(201601);
			Student row = (Student)dbss.get(Student.class, rowid);
			if(row != null){
				
				Transaction dbtr = dbss.beginTransaction(); 
				dbss.delete(row);
				dbtr.commit();
			}
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test2(){
		
		Session dbss = null;
		try{
			
			dbss = HibernateSessionFactory.getSession();
			Transaction dbtr = dbss.beginTransaction();
			String hql = "delete from Student where id='201602' ";
			int rowsAffected = dbss.createQuery(hql).executeUpdate();			
			System.out.println(rowsAffected + " rows affected.");
			
			dbtr.commit();
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void test3(){
		
		Session dbss = null;
		try{
			
			/* 连接数据库 */
			dbss = HibernateSessionFactory.getSession();
			
			// 构造一个普通的SQL语句
			Transaction dbtr = dbss.beginTransaction();
			
			String sql = "DELETE FROM `student` WHERE id='201603' ";
			int rowsAffected = dbss.createSQLQuery(sql).executeUpdate();			
			System.out.println(rowsAffected + " rows affected.");
			
			dbtr.commit();
		}
		catch(Exception e){
			
			System.out.println("出错: " + e.getMessage());
			e.printStackTrace();
		}
		finally{
			
			if(dbss != null)
				dbss.close();
		}
	}
	
	public static void main(String[] args) {
		
		//test1();
		//test2();
		test3();
	}

}

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/84959614