💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
MyBatis是一个持久化框架(替代JDBC操作数据库的) 1. 在POM.xml中加入依赖 ``` <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> </dependencies> ``` 2. 创建SqlMapConfig.xml 说明: xml约束文档有两类,dtd xsd ~~~ <?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/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/neuedu/model/dao/SuserMapper.xml"></mapper> </mappers> </configuration> ~~~ 3. 编写接口文件 ~~~ package com.neuedu.model.dao; import java.util.List; import com.neuedu.model.bo.Suser; public interface SuserMapper { public List<Suser> getAllUsers(); public void addUser(); public void deleteUser(); } ~~~ 4. 编写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.neuedu.model.dao.SuserMapper" > <select id="getAllUsers" resultType="com.neuedu.model.bo.Suser"> select * from suser </select> <insert id="addUser"> insert into suser(name,age) values ('xx',20) </insert> <delete id="deleteUser"> delete from suser where id = 2 </delete> </mapper> ~~~ 5. 运行测试程序 ~~~ InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); System.out.println(sqlSession); SuserMapper suserMapper = sqlSession.getMapper(SuserMapper.class); suserMapper.addUser(); sqlSession.commit(); ~~~ 6. 配置log4j, 将log4.propertis 放在classpath跟路径下 ~~~ # Global logging configuration #\u751F\u4EA7\u73AF\u5883\u914D\u7F6Einfo ERROR log4j.rootLogger=DEBUG,stdout # MyBatis logging configuration... log4j.logger.org.mybatis.example.BlogMapper=TRACE # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n ~~~ 加入log4j的依赖 ``` <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> ```