mybatis 使用
建立 dao entity mybatis 三个包
dao 包中主要建立的是 实体类的接口
entity包中建立的是实体类(这里不对实体类进行实现)
mybatis中建立的是实体类接口的实现
2.下边分别看几个文件的具体内容
实体类
package org.checkin.entity; public class User { private String userName; private String password; public String GetUserName() { return this.userName; } public String GetPassword() { return this.password; } public void SetUserName(String newValue) { this.userName=newValue; } public void SetPassord(String newValue) { this.password=newValue; } }
实体类的接口
package org.checkin.dao; import org.checkin.entity.User; /** * @author Administrator * */ public interface UserMapper { /** * @param Id * @return */ public User GetUserById(String Id); }
实体类接口的实现
<?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"> <!--这块等于dao接口的实现 namespace必须和接口的类路径一样--> <mapper namespace="org.checkin.dao.UserMapper"> <!-- findById必须和接口中的方法名一样 返回一个User 就是刚才的别名 如果不弄别名要连类路径一起写 麻烦--> <select id="GetUserById" parameterType="string" resultType="User"> select name as userName, ClassId as password from test.stu where id=#{id} </select> </mapper>
连接数据库 configuration.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> <typeAliases> <package name="org.checkin.entity"/> </typeAliases> <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/test?userUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="org/checkin/mybatis/UserMapper.xml" /> </mappers> </configuration>
数据库
package org.checkin.dao; import java.io.IOException; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class DataBaseCon { public static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "configuration.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sessionFactory; } }
test.java
import org.apache.ibatis.session.SqlSession; import org.checkin.dao.DataBaseCon; import org.checkin.dao.UserMapper; import org.checkin.entity.User; public class Test { @org.junit.Test public void test() { SqlSession sqlSession = DataBaseCon.getSessionFactory().openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.GetUserById("1"); System.out.println(user.GetUserName()); } }
数据库表