helloworld项目代码,请点击下链接地址,进行下载。
代码地址:点击打开链接
1、数据库脚本mysql
test 数据库:
CREATE DATABASE `test`CHARACTER SET utf8;
student表结构:
CREATE TABLE `test`.`student`( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `name` VARCHAR(32), PRIMARY KEY (`id`) );
插入两条数据:
INSERT INTO `test`.`student` (`name`) VALUES ('刘德华');
INSERT INTO `test`.`student` (`name`) VALUES ('张学友');
2、创建maven工程项目、添加mybatis依赖包和数据库驱动
<dependencies> <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.35</version> </dependency> </dependencies>3、编写全局配置文件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://192.169.2.244:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis/StudentMapper.xml"/> </mappers> </configuration>4、实体student
package com.hello.entity; public class Student { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
5、编写student的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"> <mapper namespace="com.hello.mapper.StudentMapper"> <select id="selectStudent" resultType="com.hello.entity.Student"> select * from student where id = #{id} </select> </mapper>
6、编写测试类
package com.hello; import com.hello.entity.Student; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; /** * Hello world! * */ public class App { public static void main( String[] args ) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { Student student = session.selectOne( "com.hello.mapper.StudentMapper.selectStudent", 1); System.out.println(student); } finally { session.close(); } } }7、运行结果
![]()