mybatis入门

    xiaoxiao2022-11-22  11

    1.项目结构

    2.数据库结构

    3.步骤

    (1)新建Java项目

    (2)新建lib目录导入log4j、mybatis、mysql-connector-java包

    (3)新建User类和Mybatis_test测试类

    (4)新建log4j.xml、mybatis-config.xml、sql.xml配置文件在conf目录中

    4.参考代码

    (1)User类

    package com.mybatis; public class User { private int id; private String name; private int age; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }

    (2)Mybatis_test测试类

    package com.mybatis; 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 Mybatis_test { 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{ User user = session.selectOne("com.mybatis.mapper.selectStu", 1); System.out.println(user); }finally{ session.close(); } } }

    (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://localhost:3306/lee" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="sql.xml" /> </mappers> </configuration>

    (4)sql.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="com.mybatis.mapper"> <select id="selectStu" resultType="com.mybatis.User"> select * from stu where id = #{id} </select> </mapper>

    5.运行结果

    最新回复(0)