SSM框架连接MySQL数据库的具体步骤如下:
mydb
,并创建一张表,例如user
表,用于存储用户信息。示例配置代码:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
SqlSessionFactoryBean
和MapperScannerConfigurer
,用于加载MyBatis的Mapper接口和映射文件。示例配置代码:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
com.example.mapper
包中,创建一个Mapper接口,例如UserMapper
,定义数据库操作方法。在resources/mapper
目录下,创建一个映射文件,例如UserMapper.xml
,配置SQL语句。示例Mapper接口代码:
public interface UserMapper {
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
示例映射文件代码:
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="addUser" parameterType="com.example.model.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="updateUser" parameterType="com.example.model.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
示例Service层代码:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public void addUser(User user) {
userMapper.addUser(user);
}
public void updateUser(User user) {
userMapper.updateUser(user);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
}
示例Controller层代码:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/get/{id}")
@ResponseBody
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(User user) {
userService.addUser(user);
return "redirect:/user/list";
}
// 其他操作类似...
}
这样,SSM框架就可以连接MySQL数据库,并实现基本的数据操作。以上只是一个简单示例,实际项目中可以根据需求进行更详细的配置和开发。腾讯云提供了云数据库MySQL服务,可以用于托管MySQL数据库,具体产品信息请参考:腾讯云云数据库 MySQL。
领取专属 10元无门槛券
手把手带您无忧上云