hibernate 使用sql增删改查 10
1个回答
展开全部
直接上代码,不懂的再问我吧。
package com.winwill;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
/**
* Hibernate 实现数据插入
*/
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
user u1 = new user();
u1.setName("zhangsan");
u1.setAge(25);
session.beginTransaction();
session.save(u1);
session.getTransaction().commit();
/**
* Hibernate 实现数据删除
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
user u2 = new user();
u2.setId(53); //删除id=16的项
session.delete(u2);
session.getTransaction().commit();
/**
* Hibernate 实现数据更新
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
user u3 = (user)session.get(user.class,54);
if(u3 != null){
u3.setName("lisi");
u3.setAge(23);
session.update(u3);
session.getTransaction().commit();
}
/**
* Hibernate 实现数据查询(HQL查询)
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from user where age=23"); //此处user是类名,而不是数据库的表名,select * 不写
List<user> users = query.list();
for (user user : users) {
System.out.println(user.getId()+" "+user.getName()+" "+user.getAge());
}
}
}
package com.winwill;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
/**
* Hibernate 实现数据插入
*/
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
user u1 = new user();
u1.setName("zhangsan");
u1.setAge(25);
session.beginTransaction();
session.save(u1);
session.getTransaction().commit();
/**
* Hibernate 实现数据删除
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
user u2 = new user();
u2.setId(53); //删除id=16的项
session.delete(u2);
session.getTransaction().commit();
/**
* Hibernate 实现数据更新
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
user u3 = (user)session.get(user.class,54);
if(u3 != null){
u3.setName("lisi");
u3.setAge(23);
session.update(u3);
session.getTransaction().commit();
}
/**
* Hibernate 实现数据查询(HQL查询)
*/
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from user where age=23"); //此处user是类名,而不是数据库的表名,select * 不写
List<user> users = query.list();
for (user user : users) {
System.out.println(user.getId()+" "+user.getName()+" "+user.getAge());
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询