创建数据库
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'Tom', '12'); INSERT INTO `user` VALUES ('2', 'Jack', '11');
下面是测试代码,测试目录如下:
添加log4j日志
log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
与数据库对应的javabean
package com.hb.bean; public class User { private int id; private String name; private int age; //get,set方法 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; } public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public User() { } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
配置mybatis的配置文件
<?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> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias alias="User" type="com.hb.bean.User" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="jdbc" /> <dataSource type="POOLED"> <!-- <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@192.168.56.201:1521:system"/> --> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!-- 访问数据库的映射文件 --> <mappers> <mapper resource="com/hb/bean/userDao.xml" /> <mapper class="com.hb.mapper.UserMapper" /> </mappers> </configuration>
一、访问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="com.hb.bean.userDao"> <!-- 这里namespace必须是“包名 + xml文件名”,不然要运行的时候要报错 “is not known to the MapperRegistry” --> <insert id="insertUser" parameterType="com.hb.bean.User"> insert into user(name, age) values(#{name}, #{age}); </insert> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> <update id="updateUser" parameterType="com.hb.bean.User"> update user set name=#{name},age=#{age} where id=#{id} </update> <select id="selectUser" parameterType="int" resultType="com.hb.bean.User"> select * from user where id=#{id} </select> <select id="selectAlluser" resultType="com.hb.bean.User"> select * from user </select> </mapper>
package com.hb.test1; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.hb.bean.User; public class Test1 { public static SqlSessionFactory sqlSessionFactory; public static SqlSession sqlSession; @Before public void init(){ //"/"表示是在src根目录下 String source = "config.xml"; InputStream inputStream = Test1.class.getClassLoader().getResourceAsStream(source); try { sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // sqlSession = sqlSessionFactory.openSession(); //是否自动提交,默认不是自动提交的 sqlSession = sqlSessionFactory.openSession(true); } catch (Exception e) { e.printStackTrace(); } } @Test public void add(){ String statment = "com.hb.bean.userDao.insertUser"; User user = new User(); user.setId(4); user.setAge(100); user.setName("father"); sqlSession.insert(statment, user); //添加数据需要commit,默认是不commit sqlSession.commit(); //关闭session sqlSession.close(); } @Test public void selectById(){ String statment = "com.hb.bean.userDao.selectUser"; User user = sqlSession.selectOne(statment, "1"); System.out.println(user); } @Test public void update(){ String statment = "com.hb.bean.userDao.updateUser"; User user = new User(); user.setId(1);; user.setAge(100); user.setName("mather"); sqlSession.update(statment, user); System.out.println(user); } @Test public void delete(){ String statment = "com.hb.bean.userDao.deleteUser"; sqlSession.delete(statment, 6); //添加数据需要commit,默认是不commit sqlSession.commit(); //关闭session sqlSession.close(); } }
二、访问接口操作数据库
package com.hb.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.hb.bean.User; public interface UserMapper { @Insert("insert into user(name, age) values(#{name}, #{age})") public int insertUser(User user); @Delete("delete from user where id=#{id}") public int deleteUserById(int id); @Update("update user set name=#{name},age=#{age} where id=#{id}") public int updateUser(User user); @Select("select * from user where id=#{id}") public User getUserById(int id); @Select("select * from user") public List<User> getAllUser(); }
package com.hb.test1; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import com.hb.bean.User; public class AnnotationTest1 { public static SqlSessionFactory sqlSessionFactory; public static SqlSession sqlSession; @Before public void init(){ //"/"表示是在src根目录下 String source = "config.xml"; InputStream inputStream = AnnotationTest1.class.getClassLoader().getResourceAsStream(source); try { sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // sqlSession = sqlSessionFactory.openSession(); //是否自动提交,默认不是自动提交的 sqlSession = sqlSessionFactory.openSession(true); } catch (Exception e) { e.printStackTrace(); } } @Test public void add(){ String statment = "com.hb.mapper.UserMapper.insertUser"; User user = new User(); user.setId(4); user.setAge(100); user.setName("father"); sqlSession.insert(statment, user); //添加数据需要commit,默认是不commit sqlSession.commit(); //关闭session sqlSession.close(); } @Test public void selectById(){ String statment = "com.hb.mapper.UserMapper.selectUser"; User user = sqlSession.selectOne(statment, "1"); System.out.println(user); } @Test public void update(){ String statment = "com.hb.mapper.UserMapper.updateUser"; User user = new User(); user.setId(1);; user.setAge(100); user.setName("mather"); sqlSession.update(statment, user); System.out.println(user); } @Test public void delete(){ String statment = "com.hb.mapper.UserMapper.deleteUser"; sqlSession.delete(statment, 6); //添加数据需要commit,默认是不commit sqlSession.commit(); //关闭session sqlSession.close(); } }