1.pom
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency>
2.dao
public interface UserMapper { public Info findById(Long Id); public void insert(Info info); }
3.domain
public class Info { private Long id; private String name; private Integer age; private Date time; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
4.mybatis配置 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> <!--数据源配置 --> <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://10.182.97.213:3306/test" /> <property name="username" value="root" /> <property name="password" value="xxx" /> </dataSource> </environment> </environments> <mappers> <!--userMapper.xml装载进来 --> <mapper resource="mapper/userMapper.xml" /> </mappers> </configuration>
5.mapper
<?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"> <!--相当于UserMapper接口的实现 namespace必须是UserMapper类路径--> <mapper namespace="com.jd.xq.dao.UserMapper"> <!-- findById必须和接口中的方法名一样 返回一个User--> <select id="findById" parameterType="Long" resultType="com.jd.xq.domain.Info"> select * from info where id=#{id} </select> <insert id="insert" parameterType="com.jd.xq.domain.Info"> insert into info(id,name,age,time) value (#{id},#{name},#{age},#{time}) </insert> </mapper>
6.结构图
7.MainTest
public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { UserMapper mapper = session.getMapper(UserMapper.class); Info user =mapper.findById(1L); System.out.println(user.getName()); } finally { session.close(); } }