-
package com.xdy.mybatis.jdbc;
-
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.PreparedStatement;
-
import java.sql.ResultSet;
-
import java.sql.SQLException;
-
-
public class JdbcTest {
-
-
public static void main(String[] args) {
-
-
Connection connection = null;
-
-
PreparedStatement preparedStatement = null;
-
-
ResultSet resultSet = null;
-
-
try {
-
-
Class.forName("com.mysql.jdbc.Driver");
-
-
-
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",
-
"root", "mysql");
-
-
String sql = "select * from user where username = ?";
-
-
preparedStatement = connection.prepareStatement(sql);
-
-
preparedStatement.setString(1, "王五");
-
-
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.1 問題總結
1、數據庫連接,使用時就創建,不使用立即釋放,對數據庫進行頻繁連接開啓和關閉,造成數據庫資源浪費,影響 數據庫性能。
設想:使用數據庫連接池管理數據庫連接。
2、將sql語句硬編碼到java代碼中,如果sql 語句修改,需要重新編譯java代碼,不利於系統維護。
設想:將sql語句配置在xml配置文件中,即使sql變化,不需要對java代碼進行重新編譯。
3、向preparedStatement中設置參數,對佔位符號位置和設置參數值,硬編碼在java代碼中,不利於系統維護。
設想:將sql語句及佔位符號和參數全部配置在xml中。
4、從resutSet中遍歷結果集數據時,存在硬編碼,將獲取表的字段進行硬編碼,,不利於系統維護。
設想:將查詢的結果集,自動映射成java對象。
2、入門程序
2.1 SqlMapConfig.xml
配置mybatis的運行環境,數據源、事務等。
-
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
-
<!DOCTYPE configuration
-
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
-
"http://mybatis.org/dtd/mybatis-3-config.dtd">
-
<configuration>
-
-
<environments default="development">
-
<environment id="development">
-
-
<transactionManager type="JDBC" />
-
-
<dataSource type="POOLED">
-
<property name="driver" value="com.mysql.jdbc.Driver" />
-
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
-
<property name="username" value="root" />
-
<property name="password" value="" />
-
</dataSource>
-
</environment>
-
</environments>
-
-
</configuration></span>
2.2 根據用戶id(主鍵)查詢用戶信息
2.2.1 創建po類
-
<span style="font-size:14px;">package com.xdy.mybatis.po;
-
-
import java.util.Date;
-
-
public class User {
-
private int id;
-
private String username;
-
private String sex;
-
private Date birthday;
-
private String address;
-
-
public int getId() {
-
return id;
-
}
-
-
public void setId(int id) {
-
this.id = id;
-
}
-
-
public String getUsername() {
-
return username;
-
}
-
-
public void setUsername(String username) {
-
this.username = username;
-
}
-
-
public String getSex() {
-
return sex;
-
}
-
-
public void setSex(String sex) {
-
this.sex = sex;
-
}
-
-
public Date getBirthday() {
-
return birthday;
-
}
-
-
public void setBirthday(Date birthday) {
-
this.birthday = birthday;
-
}
-
-
public String getAddress() {
-
return address;
-
}
-
-
public void setAddress(String address) {
-
this.address = address;
-
}
-
-
@Override
-
public String toString() {
-
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
-
+ address + "]";
-
}
-
-
-
}</span><span style="font-size:18px;">
-
</span>
2.2.2 映射文件
-
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
-
<!DOCTYPE mapper
-
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
-
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
<mapper namespace="test">
-
<select id="findUserById" parameterType="int" resultType="com.xdy.mybatis.po.User">
-
select * from user where id=#{value}
-
</select>
-
</mapper></span>
2.2.3 在SqlMapConfig.xml加載映射文件
-
<span style="font-size:14px;"><mappers>
-
<span style="white-space: pre;"> </span><mapper resource="sqlmap/User.xml"/>
-
</mappers></span>
2.2.4 程序編寫
-
<span style="font-size:14px;">public class MybatisFirst {
-
-
@Test
-
public void findUserByIdTest() throws IOException {
-
-
String resource = "SqlMapConfig.xml";
-
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
-
-
-
-
-
-
User user = sqlSession.selectOne("test.findUserById", 1);
-
-
System.out.println(user);
-
-
-
sqlSession.close();
-
}
-
}</span>
2.3 根據用戶名稱模糊查詢用戶信息
使用User.xml,添加根據用戶名稱模糊查詢用戶信息的sql語句。
-
<select id="findUserByName" parameterType="java.lang.String" resultType="com.xdy.mybatis.po.User">
-
select * from user where username like '%${value}%'
-
</select>
2.3.1 程序代碼
-
@Test
-
public void findUserByNameTest() throws IOException {
-
-
String resource = "SqlMapConfig.xml";
-
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
-
-
List<User> list = sqlSession.selectList("test.findUserByName", "小明");
-
-
System.out.println(list);
-
-
-
sqlSession.close();
-
}
2.4 添加用戶
2.4.1 映射文件
在 User.xml中配置添加用戶的Statement
-
<insert id="insertUser" parameterType="com.xdy.mybatis.po.User">
-
<span style="white-space:pre"> </span>insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
-
</insert>
2.4.2 程序代碼
-
<span style="white-space:pre"> </span>@Test
-
public void insertUserTest() throws IOException {
-
-
String resource = "SqlMapConfig.xml";
-
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
-
-
User user = new User();
-
user.setUsername("張三");
-
user.setBirthday(new Date());
-
user.setSex("1");
-
user.setAddress("重慶");
-
-
sqlSession.insert("test.insertUser", user);
-
-
sqlSession.commit();
-
-
System.out.println(user.getId());
-
-
-
sqlSession.close();
-
}
2.4.3 自增主鍵返回
mysql自增主鍵,執行insert提交之前自動生成一個自增主鍵。通過mysql函數獲取到剛插入記錄的自增主鍵:LAST_INSERT_ID(),是insert之後調用此函數。
修改insertUser定義:
-
<insert id="insertUser" parameterType="com.xdy.mybatis.po.User">
-
<selectKey keyProperty="id" order="AFTER" resultType="int">
-
select last_insert_id()
-
</selectKey>
-
insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
-
</insert>
2.4.5 非自增主鍵返回(使用uuid())
使用mysql的uuid()函數生成主鍵,需要修改表中id字段類型爲string,長度設置成35位。
執行思路:
先通過uuid()查詢到主鍵,將主鍵輸入 到sql語句中。
執行uuid()語句順序相對於insert語句之前執行。
通過oracle的序列生成主鍵:
-
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
-
SELECT 序列名.nextval()
-
</selectKey>
2.5 刪除用戶
2.5.1 映射文件
-
<delete id="deleteUser" parameterType="int">
-
delete from user where id=#{id}
-
</delete>
2.5.2 代碼
-
<span style="white-space:pre"> </span>@Test
-
public void deleteUserTest() throws IOException {
-
-
String resource = "SqlMapConfig.xml";
-
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
sqlSession.delete("test.deleteUser", 10);
-
sqlSession.commit();
-
-
sqlSession.close();
-
}
2.6 更新用戶
2.6.1 映射文件
-
<update id="updateUser" parameterType="com.xdy.mybatis.po.User">
-
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
-
</update>
2.6.2 代碼
-
<span style="font-size:12px;"><span style="white-space: pre;"> </span>@Test
-
public void updateUserTest() throws IOException {
-
-
String resource = "SqlMapConfig.xml";
-
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
User user = new User();
-
user.setId(16);
-
user.setUsername("張小凡");
-
user.setBirthday(new Date());
-
user.setSex("1");
-
user.setAddress("重慶市江北區");
-
sqlSession.update("test.updateUser", user);
-
sqlSession.commit();
-
-
sqlSession.close();
-
}</span>
2.7 總結
2.7.1 parameterType
在映射文件中通過parameterType指定輸入 參數的類型。
2.7.2 resultType
在映射文件中通過resultType指定輸出結果的類型。
2.7.3 #{}和${}
#{}表示一個佔位符號,#{}接收輸入參數,類型可以是簡單類型,pojo、hashmap。
如果接收簡單類型,#{}中可以寫成value或其它名稱。
#{}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。
${}表示一個拼接符號,會引用sql注入,所以不建議使用${}。
${}接收輸入參數,類型可以是簡單類型,pojo、hashmap。
如果接收簡單類型,${}中只能寫成value。
${}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。
2.7.4 selectOne和selectList
selectOne表示查詢出一條記錄進行映射。如果使用selectOne可以實現使用selectList也可以實現(list中只有一個對象)。
selectList表示查詢出一個列表(多條記錄)進行映射。如果使用selectList查詢多條記錄,不能使用selectOne。
如果使用selectOne報錯:
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4
2.8 mybatis和hibernate本質區別和應用場景
hibernate:是一個標準ORM框架(對象關係映射)。入門門檻較高的,不需要程序寫sql,sql語句自動生成了。
對sql語句進行優化、修改比較困難的。
應用場景:
適用與需求變化不多的中小型項目,比如:後臺管理系統,erp、orm、oa。。
mybatis:專注是sql本身,需要程序員自己編寫sql語句,sql修改、優化比較方便。mybatis是一個不完全 的ORM框架,雖然程序員自己寫sql,mybatis 也可以實現映射(輸入映射、輸出映射)。
應用場景:
適用與需求變化較多的項目,比如:互聯網項目。
企業進行技術選型,以低成本 高回報作爲技術選型的原則,根據項目組的技術力量進行選擇。