1、安装mysql镜像
前文中我们安装了docker和redis镜像,并在idea中成功连接,现在安装mysql镜像
docker pull mysql ,默认最新版本
ps:可以参考https://www.runoob.com/docker/docker-install-mysql.html
2、启动mysql
打开powershell,执行
docker run -itd --name mysql-test -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql
注意:这里直接用可视化界面启动,容易忘记设置端口号映射,所以选择命令行执行
3、登录mysql
在powershell中执行 mysql -h localhost -u root -p
输入密码 123456
4、 创建数据库
create datebase testDB
5、创建表
这一步可以在IDEA中执行
6、IDEA进行配置
yml:
spring:
datasource:
url: jdbc:mysql://localhost:3306/testDB?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations:
- classpath:mybatis/*.xml
pom:
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
示例:
创建mapper和po
创建mapper.xml
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.example.demov2.mapper.OrderMapper">
<resultMap id="orderMap" type="com.example.demov2.po.OrderPO">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="orderId" column="order_id" jdbcType="VARCHAR" />
<result property="userId" column="user_id" jdbcType="BIGINT" />
<result property="createTime" column="create_time" jdbcType="TIMESTAMP" />
<result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
</resultMap>
<select id="selectById" resultMap="orderMap">
select
*
from
`order`
where
`id`= #{id}
</select>
</mapper>
启动类添加注解:@MapperScan(“com.example.demov2.mapper”)
@SpringBootApplication
@MapperScan("com.example.demov2.mapper")
public class DemoV2Application {
}
7、测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class OrderServiceTest {
@Autowired
public OrderService orderService;
@Test
public void getTest() {
OrderPO orderPO = orderService.get(1);
System.out.println(orderPO);
}
}
控制台输出:
OrderPO(id=1, orderId=2, userId=3, createTime=2023-02-27T13:31:43, updateTime=2023-02-27T17:59:30)