导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
在resources目录下创建mysql.properties,写入:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/javatest?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
name=root
password=root1234
在resources目录下创建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>
<properties resource="mysql.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.mine.dao.MyuserDao"></mapper>
</mappers>
</configuration>
创建 com.mine.dao.MyuserDao 接口写入:
public interface MyuserDao {
@Select("select * from myuser ${order}")
List<Map<String,Object>> getAll(String order);
@Select("select * from myuser where id = #{id}")
Map<String,Object> getOne(Integer id);
}
调用
public class MyMain {
public static void main(String[] args) {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = builder.build(inputStream);
SqlSession sqlSession = factory.openSession(true);//开启事务
MyuserDao myUserMapper = sqlSession.getMapper(MyuserDao.class);
Map<String, Object> one = myUserMapper.getOne(2);
System.out.println(one);
System.out.println("-----------------------");
List<Map<String, Object>> all = myUserMapper.getAll("order by 1 desc");
System.out.println(all);
}
}