mybatis入门
Posted 1906859953lucas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis入门相关的知识,希望对你有一定的参考价值。
首先来回顾一下jdbc
@Test public void testJdbc(){ Connection connection=null; PreparedStatement prepareStatement=null; ResultSet resultSet=null; try { //加载驱动 Class.forName("com.mysql.jdbc.Driver"); //建立连接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8","root", "root"); //创建sql语句并执行 String sql="select * from user "; prepareStatement = connection.prepareStatement(sql); //prepareStatement.setString(1, "王五"); resultSet = prepareStatement.executeQuery(); //返回结果集并处理 while (resultSet.next()) { System.out.println(resultSet.getString("id")+"------>"+resultSet.getString("userName")); } } catch (Exception e) { e.printStackTrace(); }finally { if(resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prepareStatement!=null){ try { prepareStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
最基础的xml开发
然后再来看看mybatis
建立maven工程
file--new--project---maven--maven project--next
然后在pom中添加依赖
<dependencies> <!-- mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mysql依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
建立pojo类
public class User { private int id; private String userId; private String userName; private String birthday; private String gender; private String address; private String tel; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } @Override public String toString() { return "User [id=" + id + ", userId=" + userId + ", userName=" + userName + ", birthday=" + birthday + ", gender=" + gender + ", address=" + address + ", tel=" + tel + "]"; } }
dao接口以及实现类daoImpl
public interface UserDao { public User findUserById(int id) ; public void insertUser(User user) ; }
public class UserDaoImpl implements UserDao { // 注入SqlSessionFactory public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } private SqlSessionFactory sqlSessionFactory; @Override public User findUserById(int id) { SqlSession session = sqlSessionFactory.openSession(); User user = null; try { // 通过sqlsession调用selectOne方法获取一条结果集 // 参数1:指定定义的statement的id,参数2:指定向statement中传递的参数 user = session.selectOne("test.findUserById", id); System.out.println(user); } finally { session.close(); } return user; } @Override public void insertUser(User user) { SqlSession sqlSession = sqlSessionFactory.openSession(); try { sqlSession.insert("insertUser", user); sqlSession.commit(); } finally { sqlSession.close(); } } }
关键是配置文件
全局配置
<?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 配置文件 --> <properties resource="properties/db.properties"></properties> <!-- 配置数据源 --> <environments default="development"> <environment id="development"> <!-- 事务管理:采用的是JDBC的事务管理 --> <transactionManager type="JDBC" /> <!-- 配置数据源连接池: POOLED使用的是Mybatis自己的连接池 --> <dataSource type="POOLED"> <property name="driver" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </dataSource> </environment> </environments> <!-- 读取mapper映射文件 --> <mappers> <mapper resource="dao/UserMapper.xml" /> </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="test"> <select id="findUserById" parameterType="int" resultType="com.kkb.mybatis.dao.po.User"> SELECT * FROM user WHERE id = #{id} </select> <insert id="insertUser" parameterType="com.kkb.mybatis.dao.po.User" useGeneratedKeys="true"> INSERT INTO user (username,gender,birthday,address) VALUES (#{userName},#{gender},#{birthday},#{address}) </insert> </mapper>
db.properties
db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8 db.username=root db.password=root
log4j.properties
# Global logging configuration log4j.rootLogger=DEBUG, stdout # MyBatis logging configuration... log4j.logger.com.kkb.mybatis.mapper=DEBUG # 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
测试
public class UserDaoTest { private SqlSessionFactory sqlSessionFactory; @Before public void before() { try { // 指定全局配置文件路径 String resource = "dao/SqlMapConfig.xml"; // 加载资源文件(全局配置文件和映射文件) InputStream inputStream = Resources.getResourceAsStream(resource); // 还有构建者模式,去创建SqlSessionFactory对象 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } @Test public void testFindUserById() { UserDao dao = new UserDaoImpl(sqlSessionFactory); User user = dao.findUserById(2); System.out.println(user); } @Test public void testInsertUser() { UserDao dao = new UserDaoImpl(sqlSessionFactory); User user = new User(); user.setUserName("lucas"); user.setGender("男"); user.setAddress("上海"); // 调用dao的添加用户操作 dao.insertUser(user); // 打印通过主键返回策略生成的ID System.out.println(user.getId()); } }
控制台信息
DEBUG [main] - Logging initialized using ‘class org.apache.ibatis.logging.log4j.Log4jImpl‘ adapter. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 813656972. DEBUG [main] - Setting autocommit to false on JDBC Connection [[email protected]] DEBUG [main] - ==> Preparing: SELECT * FROM user WHERE id = ? DEBUG [main] - ==> Parameters: 2(Integer) DEBUG [main] - <== Total: 1 User [id=2, userId=001, userName=王五, birthday=2019-05-17, gender=男, address=上海, tel=110] DEBUG [main] - Resetting autocommit to true on JDBC Connection [[email protected]] DEBUG [main] - Closing JDBC Connection [[email protected]] DEBUG [main] - Returned connection 813656972 to pool. User [id=2, userId=001, userName=王五, birthday=2019-05-17, gender=男, address=上海, tel=110]
以上是关于mybatis入门的主要内容,如果未能解决你的问题,请参考以下文章
markdown [mybatis参考]关于mybatis #mybatis的一些片段