1.将mybatis库以及mysql-connector-java库加入到配置文件中; 2.将下的两个文件也加入到配置文件下,作用是让程序在预编译期可以使这两个文件夹下的文件也进行编译,代码如下:
MyBatis src/main/resources **/*.properties **/*.xml **/*.tld false src/main/java **/*.properties **/*.xml **/*.tld false
1.创建数据库表格时,方式多样,可以选择终端操作,也可以用Idea上的DataBase,还可以用DataGrip软件;
2.使用DataGrip软件,创建表格的代码如下:
CREATE DATABASE db0602; USE db0602; CREATE TABLE student (user_id INTEGER PRIMARY KEY AUTO_INCREMENT,user_name VARCHAR(200),user_des VARCHAR(200)); INSERT INTO student VALUES (NULL,'zhangsan'); INSERT INTO student VALUES (NULL,'lisi'); SELECT *FROM student ;
<?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="deve"> <environment id="deve"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!--四个属性--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db0602"/> <property name="username" value="root"/> <property name="password" value="1qaz2wsx"/> </dataSource> </environment> </environments> <mappers> <!--<mapper resource="com/lanou/mapper/StudentMapper.xml"></mapper>--> <!--自动读取所有的mapper下的xml文件--> <package name="com.lanou.mapper"/> </mappers> </configuration>
public class Student { private Integer id; private String name; }
*在Mapper文件中写要执行的方法;
*在xml文件中写操作数据库的语句;
示例,将写一条查询表中所有数据的语句.
public interface StudentMapper { //查询所有的学生 ListallListStudent(); }
<?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"> <!--namespace:一般写对应的接口路径--> <mapper namespace="com.lanou.mapper.StudentMapper"> <select id="allListStudent" resultMap="BaseMap"> SELECT * FROM student; </select> </mapper>注意:需要在config.xml中将对应的mapper加入到标签
创建BatisTest类,具体代码如下:
public class BatisTest { @Test public void test1() throws IOException { //1.加载config文件 String re = "config.xml"; InputStream stream = Resources.getResourceAsStream(re); //2.创建SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream); //3.生成SqlSession SqlSession session = factory.openSession(); //4.获取mapper对象 StudentMapper mapper = session.getMapper(StudentMapper.class); //5.调用查询所有数据的方法获得结果 Liststudents = mapper.allListStudent(); System.out.println(students); //对数据库进行修改,需要使用session提交事务 session.commit(); session.close(); } }
运行结果没毛病,作为新手入坑篇很有用.