使用Hibernate原生API實現CURD操作
阿新 • • 發佈:2018-12-30
Configuration物件:主要作用是從配置檔案hibernate.cfg.xml檔案中讀取資料的基本資訊,比如url、使用者名稱、密碼、驅動程式名稱等來連線指定的資料庫,建立SessionFactory藉口物件。
Configuration configuration = new Configuration();
3.將UserInfo.hbm.xml檔案配置進hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure(hibernate.cfg.xml路徑名);
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session物件:該物件負責進行資料的CURD操作,時Hibernate使用最頻繁的工具類,Session本身是執行緒不安全的,但是HibernateSessionFactory類中已經將Session放入了ThreadLocal中,所以HibernateSessionFactory類中的Session物件是執行緒安全的。Session本身是輕量級的,所以可以頻繁的建立或者銷燬,在效能上影響非常小。
Session操作目標表USERINFO步驟:
1.建立UserInfo實體類
2.建立UserInfo.hbm.xml,程式碼如下package orm; import java.util.Date; public class UserInfo { private long id; private String name; private String password; private long age; private Date insertDate; public long getId() { return id; } public void setId(long 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 long getAge() { return age; } public void setAge(long age) { this.age = age; } public Date getInsertDate() { return insertDate; } public void setInsertDate(Date insertDate) { this.insertDate = insertDate; } }
<hibernate-mapping> <class name="orm.UserInfo" table="USERINFO" schema="GHY"> <id name="id" type="java.lang.Long"> <column name="ID" precision="18" scale="0"/> <gennerator class="sequence"> <param name="sequence">iduto</param> </gennerator> </id> <property name="username" type="java.lang.String"> <column name="USERNAME" length="50"/> </property> <property name="password" type="java.lang.String"> <column name="PASSWORD" length="50"/> </property> <property name="age" type="java.lang.Long"> <column name="AGE" precision="18" scale="0"/> </property> <property name="insertDate" type="java.lang.Date"> <column name="INSERTDATE" length="7"/> </property> </class> </hibernate-mapping>
3.將UserInfo.hbm.xml檔案配置進hibernate.cfg.xml
4.新建新增記錄的Servlet
public class HibernateSessionFactoryTest extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
UserInfo userInfo = new UserInfo();
userInfo.setUsername("yitiananhao");
userInfo.setPassword("yitiananhao");
userInfo.setAge(23);
//通過HibernateSessionFactory獲取Session物件
Session session = HibernateSessionFactory.getSession();
//開啟事務
session.beginTransaction();
//使用session物件中的save()方法進行持久化,將UserInfo傳入
session.save(UserInfo);
//提交事務
session.beginTransaction().commit();
//關閉Session
session.close();
}
}