新建maven项目,在pom.xml导入mybatis jar包 和mysql jar包
mybatis jar包
mysql jar包
在resources建大配置
<?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"> <!--根节点,xml只能有一个--> <configuration> <properties resource="jdbc.properties"> </properties> <!--别名--> <typeAliases> <!-- <typeAlias type="cn.bdqn.entity.Studentinfo" alias="Studentinfo"></typeAlias>--> <package name="cn.bdqn.entity"></package> </typeAliases> <!--一个environments有N个environments--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/bdqn/dao/IStudentDao.xml"></mapper> </mappers> </configuration>
DAO下建小配置
<?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.bdqn.dao.IStudentDao"> <select id="getAll" resultType="Studentinfo"> SELECT * FROM studentinfo </select> <!--getstudentByid--> <select id="getstudentByid" resultType="Studentinfo"> SELECT * FROM studentinfo WHERE stuid=#{stuId} </select> <insert id="insert"> INSERT INTO studentinfo(stuName,stuAge) values(#{stuName},#{stuAge}) </insert> <!--//修改--> <update id="upd"> UPDATE studentinfo SET stuName=#{stuName}, stuAge=#{stuAge} where stuId=#{stuId} </update> <!--删除--> <delete id="del"> DELETE FROM studentinfo WHERE stuid=#{studentId} </delete> </mapper>
工具类mybatisutil
public class MyBatisUtil { private static SqlSessionFactory Factory; private static String path= "Mybatis-config.xml"; public SqlSession getsql(){ try { InputStream is= Resources.getResourceAsStream(path); Factory= new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } return Factory.openSession(); } }
测试类
@Test public void TestAll(){ String path= "Mybatis-config.xml"; try { InputStream is= Resources.getResourceAsStream(path); SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(is); SqlSession session=factory.openSession(); List<Studentinfo> list = session.selectList("getAll"); for (Studentinfo item: list) { System.out.println(item.getStuName()); } session.close(); } catch (IOException e) { e.printStackTrace(); } }