1.数据库的准备:
数据库:
create DATABASE mybatis;
数据表:
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(120) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`)
)
INSERT into user(id,username,password,gender,birthday)
VALUES
(1,'程花花','','男','1998-12-23'),
(2,'李四','','男',,'1997-03-07'),
(3,'丽丽','','女','1996-01-05'),
(4,'花花','','女','1998-10-24');
到此数据库的准备工作已经完成,接下来是搭建工程环境。
2.搭建工程环境(MyEclipse):
在MyEclipse开发工具中创建新的一个web工程,命名为MyBatisFirstDemo
创建工程
工程目录:
在lib文件夹下面,添加我们所需要的jar包:
选中右键Build Path ->Add to Build Path
所有的jar包已打包上传:
链接:https://pan.baidu.com/s/1HSxt2WX03Mq4h9eYwPkpHg
提取码:1w2h
其他工程目录的详解:
log4j.properties
#Global logging configuration
# 在开发环境下日志级别要设成
log4j.rootLogger = DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =%5p [%t] - %m%n
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>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<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_test?characterEnciding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment> </environments> <!-- 配置UserMapper.xml的映射地址 -->
<mappers>
<mapper resource="sqlmap/UserMapper.xml"/>
</mappers>
</configuration>
DataConnection .java
public class DataConnection { //MyBatis配置文件
private String resource = "SqlMapConfig.xml";
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession; public SqlSession getSqlSession() throws IOException{
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
User.java
构造器(两个),setter&getter方法
public class User implements Serializable{ private int id;
private String username;
private String password;
private String gender;
private Date birthday;
...
}
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="test">
<!-- id查询 -->
<select id="findUserByid" parameterType="int" resultType="cn.com.mybatis.po.User" >
select * from user where id=#{id}
</select> <!-- 模糊查询 -->
<select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.com.mybatis.po.User">
select * from user where username like '%${value}%'
</select> <!-- 添加数据 -->
<insert id="insertUser">
insert into user(username,password,gender,birthday)
value(#{username},#{password},#{gender},#{birthday})
</insert> <!-- drop -->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete> <!-- update -->
<update id="update" parameterType="cn.com.mybatis.po.User">
update user set username=#{username} where id=#{id}
</update>
</mapper>
MyBatisTest.java
public class MyBatisTest {
public DataConnection dataConn = new DataConnection();
//根据id进行查询
@Test
public void TestSelect() throws IOException{
SqlSession sqlSession = dataConn.getSqlSession();
User user = sqlSession.selectOne("test.findUserByid",);
System.out.println("username:" + user.getUsername());
System.out.println("password:" + user.getPassword());
System.out.println("gender:" + user.getGender()); System.out.println("birthday:" + user.getBirthday());
sqlSession.close();
} //模糊查询
@Test
public void TestFuzzySearch() throws IOException{
SqlSession sqlSession = dataConn.getSqlSession();
List<User> userList = sqlSession.selectList("test.findUserByUsername","花");
for (int i = ; i < userList.size(); i++) {
User user = userList.get(i);
System.out.println("name:" + user.getUsername());
System.out.println("password:" + user.getPassword());
System.out.println("gender:" + user.getGender());
System.out.println("birthday:" + user.getBirthday());
} sqlSession.close();
} //insert
@Test
public void TestInsert() throws IOException, ParseException{
SqlSession sqlSessions = dataConn.getSqlSession();
User user = new User();
user.setUsername("嘉佳");
user.setPassword("");
user.setGender("女"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(sdf.parse("1992-03-15")); sqlSessions.insert("test.insertUser",user);
sqlSessions.commit();
sqlSessions.close();
}
//delete
@Test
public void TestDrop() throws IOException{
SqlSession sqlSession = dataConn.getSqlSession();
sqlSession.delete("test.deleteUser",6);
sqlSession.commit();
sqlSession.close();
}
//update
@Test
public void Testupdate() throws IOException{
SqlSession sqlSession = dataConn.getSqlSession();
User user = new User();
user.setId(1);
user.setUsername("张花花");
sqlSession.update("test.update", user);
sqlSession.commit();
sqlSession.close();
}
}
注意:
测试类的创建:是下图的JUnit,在测试的时候,每个测试类上面都需要写@Test,需要调用的方法不需要加@Test
方便开发中的测试,可以不写main方法
对每个方法进行测试时可以进行单个测试,否则可能所有的测试都执行。
首先双击选中测试的类,右击选择Run As 可以看到一个Junit Test点击即可进行测试
1.根据id进行查询,此时查询到的单个记录
控制台代码(部分)
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection .
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@480bdb19]
DEBUG [main] - ==> Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: (Integer)
DEBUG [main] - <== Total:
username:花花
password:128722
gender:女
birthday:Sat Oct 24 00:00:00 CST 1998
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@480bdb19]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@480bdb19]
DEBUG [main] - Returned connection to pool.
2.模糊查询,此时查询道德可能是多个记录
控制台代码(部分)
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection .
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]
DEBUG [main] - ==> Preparing: select * from user where username like '%花%'
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total:
name:程花花
password:12345
gender:男
birthday:Wed Dec 23 00:00:00 CST 1998
name:花花
password:128722
gender:女
birthday:Sat Oct 24 00:00:00 CST 1998
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@13c27452]
3.insert 插入数据
控制台代码(部分)
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection .
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@]
DEBUG [main] - ==> Preparing: insert into user(username,password,gender,birthday) value(?,?,?,?)
DEBUG [main] - ==> Parameters: 嘉佳(String), 55555(String), 女(String), 1992-03-15 00:00:00.0(Timestamp)
DEBUG [main] - <== Updates:
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@]
数据库中:
4.delete可见在3操作中成功添加数据id=6的嘉佳
此时来测试删除该记录
控制台代码(部分)
DEBUG [main] - Created connection .
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - ==> Preparing: delete from user where id=?
DEBUG [main] - ==> Parameters: 6(Integer)
DEBUG [main] - <== Updates:
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
刷新数据库:
此时在3操作添加的记录成功删除!
5.update更新操作
id为的username为程花花貌似很难听
修改一下为张花花
控制台代码(部分)
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection .
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - ==> Preparing: update user set username=? where id=?
DEBUG [main] - ==> Parameters: 张花花(String), 1(Integer)
DEBUG [main] - <== Updates:
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd8db5a]
刷新数据库:
至此,当您看到这里,并且会单独操作,作为初学者,您已经成功入门了!