mybaties总结+hibernate总结
一、對原生態(tài)jdbc程序中問題總結
1.1 jdbc程序
需求:使用jdbc查詢mysql數(shù)據(jù)庫中用戶表的記錄
statement:向數(shù)據(jù)庫中發(fā)送一個sql語句
預編譯statement:好處:提高數(shù)據(jù)庫性能。
預編譯statement向數(shù)據(jù)庫中發(fā)送一個sql語句,數(shù)據(jù)庫編譯sql語句,并把編譯的結果保存在數(shù)據(jù)庫磚的緩存中。下次再發(fā)sql時,如果sql相同,則不會再編譯,直接使用緩存中的。
jdbc編程步驟:
1. 加載數(shù)據(jù)庫驅動
2. 創(chuàng)建并獲取數(shù)據(jù)庫鏈接
3. 創(chuàng)建jdbc statement對象
4. 設置sql語句
5. 設置sql語句中的參數(shù)(使用preparedStatement)
6. 通過statement執(zhí)行sql并獲取結果
7. 對sql執(zhí)行結果進行解析處理
8. ?釋放資源(resultSet、preparedstatement、connection)
?
public class JDBCTest {public static void main(String[] args) {Connection connection = null;// 預編譯的Statement,使用預編譯的Statement提高數(shù)據(jù)庫性能PreparedStatement preparedStatement = null;ResultSet resultSet = null;try {// 加載數(shù)據(jù)庫驅動Class.forName("com.mysql.jdbc.Driver");// 通過驅動管理類獲取數(shù)據(jù)庫鏈接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8","root", "root");// 定義sql語句 ?表示占位符String sql = "select * from t_user where username = ?";//獲取預處理statementpreparedStatement = connection.prepareStatement(sql);// 設置參數(shù),第一個參數(shù)為sql語句中參數(shù)的序號(從1開始),第二個參數(shù)為設置的參數(shù)值preparedStatement.setString(1, "王五");// 向數(shù)據(jù)庫發(fā)出sql執(zhí)行查詢,查詢出結果集resultSet = preparedStatement.executeQuery();// 遍歷查詢結果集while (resultSet.next()) {System.out.println(resultSet.getString("id") + " "+ resultSet.getString("username"));}} catch (Exception e) {e.printStackTrace();} finally {//釋放資源if (resultSet != null) {try {resultSet.close();} catch (SQLException e) {e.printStackTrace();}}if (preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}}if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}} }?
1.2問題總結
上面代碼的問題總結:
1.數(shù)據(jù)庫連接,使用時就創(chuàng)建,不使用就釋放,對數(shù)據(jù)庫進行頻繁的連接開啟和關閉,造成數(shù)據(jù)庫資源浪費,影響數(shù)據(jù)庫性能。
解決方案:使用數(shù)據(jù)庫連接池管理數(shù)據(jù)庫連接。
2.將sql語句硬編碼到Java代碼中,如果sql語句修改,需要重新編譯java代碼,不利于系統(tǒng)維護。
解決方案:將sql語句配置在xml配置文件中,即使sql變化,不需要對Java代碼進行重新編譯。
?
?
2.MyBatis框架
2.1MyBatis是什么?
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis,實質上Mybatis對ibatis進行一些改進。
MyBatis是一個優(yōu)秀的持久層框架,它對jdbc的操作數(shù)據(jù)庫的過程進行封裝,使開發(fā)者只需要關注 SQL 本身,而不需要花費精力去處理例如注冊驅動、創(chuàng)建connection、創(chuàng)建statement、手動設置參數(shù)、結果集檢索等jdbc繁雜的過程代碼。
Mybatis通過xml或注解的方式將要執(zhí)行的各種statement(statement、preparedStatemnt、CallableStatement)配置起來,并通過java對象和statement中的sql進行映射生成最終執(zhí)行的sql語句,最后由mybatis框架執(zhí)行sql并將結果映射成java對象并返回。
轉載于:https://www.cnblogs.com/ycmxm/p/7161246.html
總結
以上是生活随笔為你收集整理的mybaties总结+hibernate总结的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 三维空间两直线/线段最短距离、线段计算算
- 下一篇: 读zepto核心源码学习JS笔记(3)-
