mybatis的第一个程序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis的第一个程序相关的知识,希望对你有一定的参考价值。
1,用eclipse创建一个web项目
2,导入jar包,名字就是红框标记的
3,数据库架构
简单的一张mysql表
4,创建dao service entity
总览
UserMapper.java
package cn.abc.dao; import cn.abc.entity.User; public interface UserMapper { /** * 通过id查找User * * @return */ public User getUserById(int id); }
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="cn.abc.dao.UserMapper"> <select id="getUserById" parameterType="Integer" resultType="User"> select * from t_user where id = #{id}; </select> </mapper>
User.java
package cn.abc.entity; public class User { private int id; private String name; private String password; public User() { super(); } public User(String name, String password) { super(); this.name = name; this.password = password; } public User(int id, String name, String password) { super(); this.id = id; this.name = name; this.password = password; } 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } }
UserService.java
package cn.abc.service; import cn.abc.entity.User; public interface UserService { /** * 通过id查找User * * @return */ public User getUserById(int id); }
UserServiceImpl.java
package cn.abc.service.impl; import cn.abc.dao.UserMapper; import cn.abc.entity.User; import cn.abc.service.UserService; public class UserServiceImpl implements UserService{ //定义接口对象 private UserMapper userMapper; @Override public User getUserById(int id) { // TODO Auto-generated method stub return userMapper.getUserById(id); } }
5,在src上创建source文件夹resources,并放入以下文件
跟src是平级的 不是普通的文件夹,
jdbc.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/db_ssm?useUnicode=true&characterEncoding=utf-8 user=root password=myw123456
log4j.properties
log4j.rootLogger=DEBUG,CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %d %c - %m%n
mybatis-config.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="jdbc.properties"/> <typeAliases> <!-- <typeAlias alias="Student" type="com.abc.entity.Student"/> --> <package name="cn.abc.entity"/> </typeAliases> <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="${user}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <!-- <mapper resource="com/abc/mappers/StudentMapper.xml" /> --> <package name="cn.abc.dao"/> </mappers> </configuration>
6,mybatis工具类 MybatisUtil
代码
package cn.abc.util; import java.io.IOException; import java.io.InputStream; 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 MybatisUtil { private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getSqlSessionFactory() { try { InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("加载文件出错"); e.printStackTrace(); } return sqlSessionFactory; } public static SqlSession openSession() { return getSqlSessionFactory().openSession(); } }
7,测试类 创建junit测试类 Test001.java 注意,此处要导入junitjar包,不再贴图,因为eclipse创建junit时会自己导包的
代码
package cn.abc.test; import static org.junit.Assert.*; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import cn.abc.dao.UserMapper; import cn.abc.entity.User; import cn.abc.util.MybatisUtil; public class Test001 { private static Logger logger = Logger.getLogger(Test001.class); private SqlSession sqlSession = null; private UserMapper userMapper = null; @Before public void setUp() throws Exception { sqlSession = MybatisUtil.openSession(); userMapper = sqlSession.getMapper(UserMapper.class); } @After public void tearDown() throws Exception { sqlSession.close(); } @Test public void test() { User user = userMapper.getUserById(1); System.out.println(user.toString()); } }
运行结果
name怎么是null呢。经查找是数据库名称与类的名称不匹配所致。
8,解决错误
修改数据库中的属性
修改前
修改后
注意,修改了name
重新运行test001.java测试
ok,成功了。出现错误的原因是实体类与数据库不匹配所致,以后要多加注意。
以上是关于mybatis的第一个程序的主要内容,如果未能解决你的问题,请参考以下文章