一、项目搭建
maven项目搭建
添加web项目
二、项目pom文件依赖
注:打包方式为war
<packaging>war</packaging>
内置Tomcat
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!--端口号-->
<port>8080</port>
<!--访问路径-->
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
添加所需依赖
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
</dependencies>
三、各配置文件
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/music?useSSL=false&useUnicode=true
jdbc.user=root
jdbc.password=123456
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error">
<!--先定义所有的appender -->
<appenders>
<!--这个输出控制台的配置 -->
<Console name="Console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY"/>
<!--输出日志的格式 -->
<PatternLayout
pattern=" %highlight{%-5level %L - %msg%xEx%n}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=cyan,TRACE=blue}"/>
</Console>
</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
<loggers>
<Logger name="cn.fc.dao" level="TRACE" additivity="false">
<AppenderRef ref="asyncsql" />
</Logger>
<root level="debug">
<appender-ref ref="RollingFile"/>
<appender-ref ref="Console"/>
<appender-ref ref="ERROR"/>
<appender-ref ref="log"/>
</root>
</loggers>
</configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描指定包下的注解-->
<context:component-scan base-package="com.fc">
<!--不扫描@Controller注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--导入properties配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
<!--加载mybatis-config配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置通知(增强)-->
<tx:advice id="musicAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="select*" read-only="true" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="add*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="insert*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="delete*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="drop*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="update*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="modify*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
<tx:method name="change*" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5000"/>
</tx:attributes>
</tx:advice>
<!--aop配置-->
<aop:config>
<!--配置切点-->
<aop:pointcut id="pointcut" expression="execution(* com.fc.service.impl.*ServiceImpl.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="musicAdvice" pointcut-ref="pointcut"/>
</aop:config>
<!--注解式事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--扫描dao层接口,用来生成代理对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.fc.dao"/>
</bean>
</beans>
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>
<!--mybatis设置-->
<settings>
<!--启用二级缓存-->
<setting name="cacheEnabled" value="true"/>
<!--启用延时加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--每种属性按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
<!--开启将下划线映射到驼峰命名的规则规则-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--允许多种结果集从一个单独的语句中返回-->
<setting name="multipleResultSetsEnabled" value="true"/>
<!--使用列标签代替列名-->
<setting name="useColumnLabel" value="true"/>
<!--允许插入数据中设置主键并返回-->
<setting name="useGeneratedKeys" value="true"/>
<!--设置默认执行器-->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!--设置超时时间-->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<!--起别名-->
<typeAliases>
<typeAlias type="com.fc.bean.TbMusic" alias="tbMusic"/>
<typeAlias type="com.fc.bean.TbSheet" alias="tbSheet"/>
</typeAliases>
<!--pageHelper-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--方言,告知pageHelper对哪种数据库进行分页-->
<property name="helperDialect" value="mysql"/>
<!--合理化分页参数-->
<property name="reasonable" value="true"/>
<!--通过mapper接口传参-->
<property name="supportMethodsArguments" value="true"/>
</plugin>
</plugins>
<!--声明映射文件的位置-->
<mappers>
<mapper resource="com/fc/mapper/TbMusicMapper.xml"/>
<mapper resource="com/fc/mapper/TbSheetMapper.xml"/>
</mappers>
</configuration>
springMvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描controller包下的注解-->
<context:component-scan base-package="com.fc.controller"/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<!--<property name="prefix" value=""/>-->
<!--后缀-->
<!--<property name="suffix" value=""/>-->
</bean>
<!--mvc注解支持-->
<mvc:annotation-driven/>
<!--放行静态资源-->
<mvc:default-servlet-handler/>
<!--跨域支持-->
<mvc:cors>
<mvc:mapping path="/**"/>
</mvc:cors>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--applicationContext配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--字符编码集过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
四、项目代码实现
实体类
package com.fc.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class TbMusic implements Serializable {
private Integer musicId;
private String musicName;
private String musicAlbumName;
private String musicAlbumPicUrl;
private String musicMp3Url;
private String musicArtistName;
private Integer sheetId;
}
package com.fc.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TbSheet implements Serializable {
private Integer id;
private String sheetName;
}
dao
package com.fc.dao;
import com.fc.bean.TbMusic;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
// dao层接口
@Repository
public interface TbMusicDao {
// 查询全部歌曲
List<TbMusic> findAll();
// 根据id获取对应的歌曲
TbMusic findById(@Param("musicId") Integer musicId);
// 根据关键字模糊查询
List<TbMusic> search(@Param("keyword") String keyword);
}
package com.fc.dao;
import com.fc.bean.TbMusic;
import com.fc.bean.TbSheet;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TbSheetDao {
// 获取所有的歌单
List<TbSheet> findAll();
List<TbMusic> findSongsBySheet(@Param("sheetName") String sheetName);
int insertSheet(@Param("sheetName") String sheetName);
}
service
package com.fc.service;
import com.fc.bean.TbMusic;
import java.util.List;
// 业务层接口
public interface TbMusicService {
List<TbMusic> findAll();
TbMusic findById(Integer musicId);
TbMusic prevSong(Integer musicId);
TbMusic nextSong(Integer musicId);
List<TbMusic> search(String keyword);
}
package com.fc.service;
import com.fc.bean.TbMusic;
import com.fc.bean.TbSheet;
import java.util.List;
public interface TbSheetService {
List<TbSheet> findAll();
List<TbMusic> findSongsBySheet(String sheetName);
int insertSheet(String sheetName);
}
package com.fc.service.impl;
import com.fc.bean.TbMusic;
import com.fc.dao.TbMusicDao;
import com.fc.service.TbMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TbMusicServiceImpl implements TbMusicService {
@Autowired
private TbMusicDao tbMusicDao;
@Override
public List<TbMusic> findAll() {
return tbMusicDao.findAll();
}
@Override
public TbMusic findById(Integer musicId) {
return tbMusicDao.findById(musicId);
}
@Override
public TbMusic prevSong(Integer musicId) {
List<TbMusic> list = tbMusicDao.findAll();
// 声明一个下标,代表当前歌曲所在歌单中的位置
int index = 0;
// 循环
for (int i = 0; i < list.size(); i++) {
// 如果当前传递的id和列表中对象的id相同
if (musicId.equals(list.get(i).getMusicId())) {
// 获取当前的位置赋值给index
index = i ;
break;
}
}
// 判断当前歌曲是否在歌曲列表中的第一首的位置
index = index == 0 ? list.size() - 1 : index - 1;
// 返回当前位置的上一首歌曲对象
return list.get(index);
}
@Override
public TbMusic nextSong(Integer musicId) {
// 获取歌曲列表
List<TbMusic> list = tbMusicDao.findAll();
// 声明当前歌曲所在的下标位置
int index = 0;
for (int i = 0; i < list.size(); i++) {
if (musicId.equals(list.get(i).getMusicId())) {
index = i ;
break;
}
}
// 判断,如果当前歌曲是最后一首,拿到第一首的下标
// 否则拿到下一首的下标
index = index == list.size() - 1 ? 0 : index + 1;
return list.get(index);
}
@Override
public List<TbMusic> search(String keyword) {
return tbMusicDao.search("%" + keyword + "%");
}
}
package com.fc.service.impl;
import com.fc.bean.TbMusic;
import com.fc.bean.TbSheet;
import com.fc.dao.TbSheetDao;
import com.fc.service.TbSheetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TbSheetServiceImpl implements TbSheetService {
@Autowired
private TbSheetDao tbSheetDao;
@Override
public List<TbSheet> findAll() {
return tbSheetDao.findAll();
}
@Override
public List<TbMusic> findSongsBySheet(String sheetName) {
return tbSheetDao.findSongsBySheet(sheetName);
}
@Override
public int insertSheet(String sheetName) {
return tbSheetDao.insertSheet(sheetName);
}
}
mapper
<?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,但是有一定的规范,必须和dao层接口名相同(完整的全限定名),必须唯一-->
<mapper namespace="com.fc.dao.TbMusicDao">
<!--二级缓存-->
<cache/>
<!--查询全部-->
<select id="findAll" resultType="tbMusic">
select * from tb_music
</select>
<!--根据id获取对应的歌曲对象-->
<select id="findById" parameterType="java.lang.Integer" resultType="tbMusic">
select * from tb_music where music_id = #{musicId}
</select>
<select id="search" parameterType="java.lang.String" resultType="tbMusic">
select * from tb_music where music_name like #{keyword}
</select>
</mapper>
<?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,但是有一定的规范,必须和dao层接口名相同(完整的全限定名),必须唯一-->
<mapper namespace="com.fc.dao.TbSheetDao">
<!--二级缓存-->
<cache/>
<select id="findAll" resultType="tbSheet">
select * from tb_sheet
</select>
<select id="findSongsBySheet" parameterType="java.lang.String" resultType="tbMusic">
select music.*
from tb_music music
inner join tb_sheet as sheet
on music.sheet_id = sheet.id
where sheet.sheet_name = #{sheetName}
</select>
<insert id="insertSheet" parameterType="java.lang.String">
insert into tb_sheet(sheet_name) values (#{sheetName})
</insert>
</mapper>
controller
package com.fc.controller;
import com.fc.bean.TbMusic;
import com.fc.service.TbMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("music")
public class TbMusicController {
@Autowired
private TbMusicService tbMusicService;
@RequestMapping("findAll")
public List<TbMusic> findAll() {
return tbMusicService.findAll();
}
// 根据id获取歌曲对象
@RequestMapping("findById")
public TbMusic findById(Integer musicId) {
return tbMusicService.findById(musicId);
}
// 上一首
@RequestMapping("prevSong")
public TbMusic prevSong(Integer musicId) {
return tbMusicService.prevSong(musicId);
}
// 上一首
@RequestMapping("nextSong")
public TbMusic nextSong(Integer musicId) {
return tbMusicService.nextSong(musicId);
}
// 模糊查询
@RequestMapping("search")
public List<TbMusic> search(String keyword) {
return tbMusicService.search(keyword);
}
}
package com.fc.controller;
import com.fc.bean.TbMusic;
import com.fc.bean.TbSheet;
import com.fc.service.TbSheetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("sheet")
public class TbSheetController {
@Autowired
private TbSheetService tbSheetService;
@RequestMapping("findAll")
public List<TbSheet> findAll() {
return tbSheetService.findAll();
}
@RequestMapping("findSongsBySheet")
public List<TbMusic> findSongsBySheet(@RequestParam(value = "sheetName", required = true) String sheetName) {
return tbSheetService.findSongsBySheet(sheetName);
}
@RequestMapping("insertSheet")
public Map<String, Object> insertSheet(String sheetName) {
int affectedRows = tbSheetService.insertSheet(sheetName);
HashMap<String, Object> map = new HashMap<String, Object>();
// Map<String, Object> map = new HashMap<>();
map.put("success", false);
if (affectedRows > 0) {
map.put("success", true);
}
return map;
}
}
五、实现效果
tMapping(“findAll”)
public List findAll() {
return tbSheetService.findAll();
}
@RequestMapping("findSongsBySheet")
public List<TbMusic> findSongsBySheet(@RequestParam(value = "sheetName", required = true) String sheetName) {
return tbSheetService.findSongsBySheet(sheetName);
}
@RequestMapping("insertSheet")
public Map<String, Object> insertSheet(String sheetName) {
int affectedRows = tbSheetService.insertSheet(sheetName);
HashMap<String, Object> map = new HashMap<String, Object>();
// Map<String, Object> map = new HashMap<>();
map.put(“success”, false);
if (affectedRows > 0) {
map.put("success", true);
}
return map;
}
}
# 五、实现效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/bf4659f9abe347e4949c0e0ca83b9ce0.png#pic_center)