Java使用mybatis 查询数据库表明是否存在(配置文件为yml)
时间: 2024-01-12 09:03:17 浏览: 26
可以使用Mybatis中的Mapper接口和Mapper XML文件来实现查询数据库表是否存在的功能。具体步骤如下:
1. 创建Mapper接口,定义查询方法。
```java
public interface TableMapper {
boolean isTableExist(@Param("tableName") String tableName);
}
```
2. 创建Mapper XML文件,编写SQL语句。
```xml
<mapper namespace="com.example.mapper.TableMapper">
<select id="isTableExist" resultType="boolean">
SELECT COUNT(*) > 0 FROM information_schema.tables WHERE table_name = #{tableName}
</select>
</mapper>
```
3. 在application.yml文件中配置数据源和Mybatis。
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydatabase
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
```
4. 在Java代码中调用Mapper接口的查询方法。
```java
@Autowired
private TableMapper tableMapper;
public boolean isTableExist(String tableName) {
return tableMapper.isTableExist(tableName);
}
```
这样就可以通过调用isTableExist方法来查询指定的数据库表是否存在了。