SSM(Spring+Spring MVC+MyBatis)是一种常用的Java Web开发框架,用于快速构建企业级应用程序。下面是SSM连接数据库MySQL的步骤:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
application.properties
或application.yml
。以下是一个示例配置:# MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false&characterEncoding=utf8
spring.datasource.username=your-username
spring.datasource.password=your-password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
<!-- 数据源配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${spring.datasource.url}" />
<property name="username" value="${spring.datasource.username}" />
<property name="password" value="${spring.datasource.password}" />
<property name="driverClassName" value="${spring.datasource.driver-class-name}" />
</bean>
<!-- SqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 设置MyBatis映射文件位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
// UserMapper.java
public interface UserMapper {
User getUserById(int id);
}
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
// UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
}
这样,SSM框架就能够成功连接MySQL数据库并执行SQL语句。
关于腾讯云相关产品和产品介绍的链接,可以参考以下腾讯云文档:
领取专属 10元无门槛券
手把手带您无忧上云