【mybatis】学习笔记 1配置 搭建 入门案例
将接口,普通的java对象映射成数据库中的记录 mybatis 简化 jdbc
JDBC的数据连接
package com.mybatis;
import java.sql.*;
public class sql {
public static void main(String[] args) {
Connection con = null; //连接对象
PreparedStatement prs = null; //查询对象
ResultSet rs = null; //结果集
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //加载驱动类
String url = "jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC";
String user ="root";
String password = "88888888";
con = DriverManager.getConnection(url, user, password);///获取连接
String sql = "select * from user where u_sex = ?";
prs = con.prepareStatement(sql);
prs.setInt(1,0);
rs = prs.executeQuery(); //输出结果
while(rs.next()) {
System.out.println(rs.getString("u_id") +" "+rs.getString("u_username"));
}
}
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("连接异常");
}
finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
prs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
mybatis
导包 :
配置文件
http://www.mybatis.org/mybatis-3/zh/getting-started.html(映射sql文件 以及配置文件)
约束导入 通过下面的方法
通过ID 修改数据库
https://www.imooc.com/qadetail/248450?lastmedia=1
sqlMapConfig.xml 的配置
<?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"/>
<!-- 小型配置文件的相对路径 以及 driver =url 的值!!!!!! -->
<dataSource type="POOLED"><!-- 连接池连接数据库 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/><!-- 加载驱动类 -->
<property name="url" value="jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC"/><!-- useSSL=false -->
<property name="username" value="root"/>
<property name="password" value="88888888"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/><!-- 复制导入mapper -->
</mappers>
</configuration>
userdao类: 变量要用包装类!!!
package com.bean;
import java.util.Date;
public class user {
//用包装类 减少一些问题
private Integer u_id;
private String u_username;
private String u_password;
private String u_sex;
private Integer u_cid;
private Date u_createtime;
public Integer getU_id() {
return u_id;
}
public void setU_id(Integer u_id) {
this.u_id = u_id;
}
public String getU_username() {
return u_username;
}
public void setU_username(String u_username) {
this.u_username = u_username;
}
public String getU_password() {
return u_password;
}
public void setU_password(String u_password) {
this.u_password = u_password;
}
public String getU_sex() {
return u_sex;
}
public void setU_sex(String u_sex) {
this.u_sex = u_sex;
}
public Integer getU_cid() {
return u_cid;
}
public void setU_cid(Integer u_cid) {
this.u_cid = u_cid;
}
public Date getU_createtime() {
return u_createtime;
}
public void setU_createTime(Date u_createTime) {
this.u_createTime = u_createTime;
}
@Override
public String toString() {
return "dao [u_id=" + u_id + ", u_username=" + u_username + ", u_password=" + u_password + ", u_sex=" + u_sex
+ ", u_cid=" + u_cid + ", u_createtime=" + u_createtime + "]";
}
}
userMapper.xml 查询文件的配置!!!
<?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="UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="com.bean.user">
select * from user where u_id = #{id}
</select>
</mapper>
测试类:
package com.mybatis;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.bean.user;
public class test {
@Test // 通过id 查询用户
public void test() throws IOException {
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource); // 读出配置文件
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder(); // 创建sqlsession Factory Builder
SqlSessionFactory ssf= ssfb.build(in); // 生产一个sqlsessionfactor
SqlSession session = ssf.openSession();;
//sql语句的查询
user s = session.selectOne("UserMapper.selectUserById",1); // 操作数据库
System.out.println(s);
}
}
用户名模糊查找!!!
<select id="selectUserByName" parameterType="String" resultType="com.bean.user">
select * from user where u_username like '%${value}%'
</select>
List<user> s = session.selectList("UserMapper.selectUserByName","王"); // 操作数据库
for(user e : s) { //foreach 输出
System.out.println(e);
}
报警告WARNING: An illegal reflective access operation has occurred版本太高
字符串拼接${value} 跟占位符的区别 #{id}
字符串拼接易发生异常注入问题 1=1
要改写为占位符 ${value} => "%"#{value}"%"
添加一个用户
事务要提交!!!!
小心userdao 不要错了 大小写问题 !!!Date错了找了好久!!! 跟数据库的字段大小一致!!!
user u = new user();
u.setU_username("陈耿聪");
u.setU_password("820882");
u.setU_sex("1");
u.setU_cid(1);
session.insert("UserMapper.insertUser",u); // 操作数据库
session.commit();
插入配置的语句
<insert id="insertUser" parameterType="com.bean.user">
insert into user values(null , #{u_username},#{u_password},#{u_sex},null,#{u_cid})
</insert>
修改用户
user u = new user();
u.setU_id(13);
u.setU_username("cznczai");
session.update("UserMapper.updateUser",u); // 操作数据库
session.commit();
配置文件为
<update id="updateUser" parameterType="com.bean.user">
update user set u_username = #{u_username} where u_id = #{u_id}
</update>
删除用户
u.setU_username("陈耿聪");
session.delete("UserMapper.deleteUserByname",u); // 操作数据库
session.commit();
配置文件:
<delete id="deleteUserByname" parameterType="String>
delete from user where u_username = #{u_username}
</delete>
mybatis DAO开发!!!
UserMapper.xml和SqlMapConfig.xml 依旧不变
userdao.class
package com.my.dao;
import com.bean.user;
public interface userdao {
//根据查询id用户
public user getId(Integer id) ;
}
userdaoImpl.class
把之前test 文件进行拆分
package com.my.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.bean.user;
//ctrl + shift + o 删除没用到的包
public class userdaoImpl implements userdao {
private SqlSessionFactory ssf; //sqlSessionFactory
//alt shift + s -> Generate Constructor ...... //生成构造器
public userdaoImpl(SqlSessionFactory ssf) { //通过构造器给ssf赋值
super();
this.ssf = ssf;
}
public user getId(Integer id) {
SqlSession session = ssf.openSession();
return session.selectOne("UserMapper.selectUserById",id);
}
}
userdaoTest
package com.mybatis;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.bean.user;
import com.my.dao.userdao;
import com.my.dao.userdaoImpl;
public class UserDaoTest {
private static SqlSessionFactory ssf;
static {
try {
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
ssf = ssfb.build(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void DaoTest() {
userdao Dao = new userdaoImpl(ssf);
user u = Dao.getId(1);
System.out.println(u);
}
}
重复代码进行合并 并简化操作代码 剩下两行!!!!
mybatis >> jdbc
spell报错 拼写报错可以屏蔽