2.mybatis入门实例 连接数据库进行查询
1.新建项目,添加mybatis和mysql的jar包
2.在mysql中新建表user[id,name,age]
CREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `NAME` varchar(50) default NULL, `age` int(11) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
3.新建User类,与db的表对应
public class User { public User() { } public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
4.在src目录下面新建mybatis的配置文件conf.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> <!-- development:开发模式 work:工作模式 --> <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?autoReconnect=true&useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration>
5.新建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的标签,在此要在Window-Preference-Xml Catalog中配置mybatis-3-mapper.dtd, key=-//mybatis.org//DTD Mapper 3.0//EN --> <mapper namespace="com.mlxs.mybatis.test.userMapper"> <select id="getUser" parameterType="int" resultType="com.mlxs.mybatis.test1.User"> select * from users where id=#{id} </select> <!-- 添加,参数是一个user对象 --> <insert id="addUser" parameterType="com.mlxs.mybatis.test1.User"> insert into users(name,age) values(#{name},#{age}) </insert> <!-- 更新,参数是一个user对象 --> <insert id="updateUser" parameterType="com.mlxs.mybatis.test1.User"> update users set name=#{name}, age=#{age} where id=#{id} </insert> <!-- 添加,参数是一个user对象 --> <insert id="deleteUser" parameterType="int"> delete from users where id=#{id} </insert> <!-- 返回一个list,resultType="包名+类名":必须在类中有个无参的构造函数,不然会报错: java.lang.NoSuchMethodException: com.mlxs.mybatis.test1.User.<init>() Caused by: java.lang.NoSuchMethodException: com.mlxs.mybatis.test1.User.<init>() at java.lang.Class.getConstructor0(Class.java:2706) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.apache.ibatis.reflection.factory.DefaultObjectFactory.instantiateClass(DefaultObjectFactory.java:57) --> <select id="selectAllUsers" resultType="com.mlxs.mybatis.test1.User"> select * from users </select> </mapper>
将mapper配置文件添加到mybatis的配置文件conf.xml的mappers标签中:
<!-- 在conf.xml文件中注册Mapper.xml文件和Mapper类 --> <mappers> <mapper resource="com/mlxs/mybatis/test1/userMapper.xml" /> </mappers>
6.添加测试类,获取一个user的信息
import java.io.IOException; import java.io.InputStream; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class _Test1SelectOne { public static void main(String[] args) throws IOException { //加载mybatis的xml文件(同时加载加载关联的映射文件) //1.使用类加载器加载mybatis的配置文件 // InputStream config = _Test1SelectOne.class.getClassLoader().getResourceAsStream("conf.xml"); //2.使用mybatis的Resources类加载 Reader config = Resources.getResourceAsReader("conf.xml"); //创建sqlSessionFactory SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(config); //创建sqlSession,执行mapper.xml中的sql语句 SqlSession sqlSession = sessionFactory.openSession(); //执行映射文件中的sql(namespace + select的id) String sql = "com.mlxs.mybatis.test.userMapper.getUser"; User user = sqlSession.selectOne(sql, "1");//查询id=1 //关闭session sqlSession.close(); System.out.println(user); } }
7.结果
User [id=1, name=Tom, age=12]
8.测试 增删改查,导入junit包,添加测试类
import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Test; import com.mlxs.mybatis.util.MyBatisUtil; public class _Test2UserCrud { @Test public void addUser(){ SqlSessionFactory sessionFactory = MyBatisUtil.getSessionFactory(); SqlSession sqlSession = sessionFactory.openSession(); String statement = "com.mlxs.mybatis.test.userMapper.addUser"; int count = sqlSession.insert(statement, new User(0, "add1", 10)); sqlSession.commit(); sqlSession.close(); System.out.println("add count:"+count); } @Test public void updateUser(){ SqlSessionFactory sessionFactory = MyBatisUtil.getSessionFactory(); SqlSession sqlSession = sessionFactory.openSession(); String statement = "com.mlxs.mybatis.test.userMapper.updateUser"; int count = sqlSession.update(statement, new User(3, "update2", 100)); sqlSession.commit(); sqlSession.close(); System.out.println("update count:"+count); } @Test public void delUser(){ SqlSessionFactory sessionFactory = MyBatisUtil.getSessionFactory(); boolean autoCommit = true;//自动提交,不需手动commit SqlSession sqlSession = sessionFactory.openSession(autoCommit); String statement = "com.mlxs.mybatis.test.userMapper.deleteUser"; int count = sqlSession.delete(statement, 4); sqlSession.close(); System.out.println("del count:"+count); } @Test public void selectAll(){ SqlSessionFactory sessionFactory = MyBatisUtil.getSessionFactory(); boolean autoCommit = true;//自动提交,不需手动commit SqlSession sqlSession = sessionFactory.openSession(autoCommit); String statement = "com.mlxs.mybatis.test.userMapper.selectAllUsers"; List<User> userList = sqlSession.selectList(statement); sqlSession.close(); System.out.println(userList); } }
逃避不一定躲得过,面对不一定最难过