项目结构:
User实体类代码:
package com.atguigu.mybatis.bean; public class User { private int id; private String name; private int age; public User() { super(); } public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = 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 + "]"; } }
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="com.atguigu.mybatis.bean.userMapper"> <!-- CRUD操作 --> <insert id="addUser" parameterType="User"> insert into users(name,age) values(#{name},#{age}) </insert> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <update id="updateUser" parameterType="User"> update users set name=#{name},age=#{age} where id=#{id} </update> <select id="getUser" parameterType="int" resultType="User"> select * from users where id=#{id} </select> <select id="getAllUsers" resultType="User"> select * from users </select> </mapper>
UserMapper注解类代码(要么用xml方式,要么用注解方式):
package com.atguigu.mybatis.test2; 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.atguigu.mybatis.bean.User; public interface UserMapper { @Insert("insert into users(name,age) values(#{name},#{age})") public int add(User user); @Delete("delete from users where id=#{id}") public int deleteById(int id); @Update("update users set name=#{name},age=#{age} where id=#{id}") public int update(User user); @Select("select * from users where id=#{id}") public User getById(int id); @Select("select * from users") public List<User> getAll(); }
获取SqlSessionFactory工厂的MybatisUtils代码:
package com.atguigu.mybatis.utils; import java.io.InputStream; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisUtils { public static SqlSessionFactory getFactory() { String resource = "conf.xml"; InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); return factory; } }
配置文件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> <properties resource="db.properties"/> <!-- 为实体类定义别名,简化sql映射xml文件中的引用--> <typeAliases> <!-- <typeAlias type="com.atguigu.mybatis.bean.User" alias="User"/> --> <!-- 该包下的所有类以其简单类名为实体类别名(如:User类的别名为User) --> <package name="com.atguigu.mybatis.bean"/> </typeAliases> <!-- development : 开发模式 work : 工作模式 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${name}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/atguigu/mybatis/bean/userMapper.xml"/> <mapper class="com.atguigu.mybatis.test2.UserMapper"/> </mappers> </configuration>
测试类Test2代码:
package com.atguigu.mybatis.test2; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Test; import com.atguigu.mybatis.bean.User; import com.atguigu.mybatis.utils.MybatisUtils; /* * 测试: CRUD操作的XML的实现和注解实现 */ public class Test2 { //--------------------------------测试XML的实现 @Test public void testAdd(){ SqlSessionFactory factory=MybatisUtils.getFactory(); //默认是手动提交的 SqlSession session=factory.openSession(); String statement="com.atguigu.mybatis.bean.userMapper.addUser"; int insert=session.insert(statement, new User(-1, "KK", 23)); //提交事务 session.commit(); session.close(); System.out.println(insert); } @Test public void testUpdate(){ SqlSessionFactory factory=MybatisUtils.getFactory(); //默认是手动提交 SqlSession session=factory.openSession(true); String statement = "com.atguigu.mybatis.bean.userMapper.updateUser"; int update =session.update(statement,new User(3, "KKK111", 25)); session.close(); System.out.println(update); } @Test public void testDelete(){ SqlSessionFactory factory=MybatisUtils.getFactory(); //默认是手动提交 SqlSession session=factory.openSession(true); String statement = "com.atguigu.mybatis.bean.userMapper.deleteUser"; int delete =session.delete(statement,3); session.close(); System.out.println(delete); } @Test public void testGetUser(){ SqlSessionFactory factory=MybatisUtils.getFactory(); //默认是手动提交 SqlSession session=factory.openSession(true); String statement = "com.atguigu.mybatis.bean.userMapper.getUser"; User user=session.selectOne(statement, 1); session.close(); System.out.println(user); } @Test public void testGetAll(){ SqlSessionFactory factory=MybatisUtils.getFactory(); //默认是手动提交 SqlSession session=factory.openSession(true); String statement = "com.atguigu.mybatis.bean.userMapper.getAllUsers"; List<User> list=session.selectList(statement); session.close(); System.out.println(list); } //--------------------------------测试注解的实现 @Test public void testAdd2(){ SqlSessionFactory factory=MybatisUtils.getFactory(); SqlSession session=factory.openSession(true); UserMapper mapper=session.getMapper(UserMapper.class); int add=mapper.add(new User(-1, "SS", 34)); session.close(); System.out.println(add); } }
数据库配置代码db.properties:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis name=root password=123456
可以在src下加入log4j的配置文件,打印日志信息:
-->首先添加 log4j-1.2.16.jar
-->然后:
log4j.properties(方式一)
log4j.properties, 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
log4j.xml(方式二)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>
时间: 2024-10-15 09:28:46