SpringBoot整合Jsf、Jpa实现增删改查
代码见gitee仓库
J2EE_Study: 旧技术的学习与SpringBoot新框架的整合
新建一个项目或模块
-
选用SpringBoot 初始化模板或
-
选用空的maven工程,之后添加依赖,这里采用第一种方式比较方便.
如果采用第二种方式 直接引入依赖即可(后面贴出依赖坐标集合)
选择你想用的包名 和jdk版本和对应的语言级别
比如SpringBoot3.1 需要17版本的jdk
我这里选择jdk8做演示
点击下一步,选择需要的依赖
这两个依赖大家应该很熟悉了
第一个是热部署工具 ,作用就是修改完代码后不用重启项目 ,项目自动重新部署,主要为了方便调试. (需要勾选i打开dea的自动构建功能——具体操作在设置里搜索 auto(英)或者自动构建(中)后就可以看到 ,勾选即可)。
第二个是lombok(常用) ,利用注解自动实现getset 构造方法 重写toString等 不用写代码。
下一个 web核心
然后就是jpa和对应数据库驱动
点击 创建 等一会下载好模板即可
引入其他需要的依赖 我们用jsf做前端的话 还需要引入一些必须依赖
我在这里贴出pom文件内容
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.12</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.jpa</groupId> <artifactId>SpringBootJpaDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBootJpaDemo</name> <description>SpringBootJpaDemo</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!-- 缓存支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>8.0</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.20</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.20</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>org.ocpsoft.rewrite</groupId> <artifactId>rewrite-servlet</artifactId> <version>3.4.1.Final</version> </dependency> <!--common工具包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.mpxj/mpxj --> <dependency> <groupId>net.sf.mpxj</groupId> <artifactId>mpxj</artifactId> <version>9.0.0</version> <exclusions> <exclusion> <artifactId>jakarta.activation</artifactId> <groupId>com.sun.activation</groupId> </exclusion> </exclusions> </dependency> <!-- https://mvnrepository.com/artifact/jakarta.faces/jakarta.faces-api --> <dependency> <groupId>jakarta.faces</groupId> <artifactId>jakarta.faces-api</artifactId> <version>3.0.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/**</include> <include>WEB-INF/*.*</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
maven最好使用自己安装的 idea自带的有bug
搜索maven设置 修改对应的setting文件 主要修改 本地仓库和国内镜像源(自行百度)
这里改完 setting文件后 自动识别你写在文件中的本地仓库地址
安装好后 重新加载 项目 等待依赖下载完成——pom文件 不飘红即可
建立如下项目结构 右键项目 ->打开模块设置
src main java resources webapp
同理在webapp下新增WEB-INF文件夹,
在WEB-INF文件下新增web.xml及face-config.xml
在刚才新建的项目目录WEB-INF下面新建一个xml文件 命名为web.xml 文件内容是
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> </web-app>
在刚才新建的项目目录WEB-INF下面新建一个xml文件 命名为faces-config.xml 文件内容是
<?xml version="1.0" encoding="UTF-8"?> <faces-config 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-facesconfig_2_2.xsd" version="2.2"> <name>gantt365</name> <lifecycle> <phase-listener>org.springframework.web.jsf.DelegatingPhaseListenerMulticaster</phase-listener> </lifecycle> <application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application> </faces-config>
web资源目录 选择 刚才的webapp
注意观察目录结构文件夹颜色 要正确
修改配置文件 application.properties 增加数据源配置等 当然熟悉yml文件的同学可以用yml文件是一样的
#datasource spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123 #jpa配置 spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
main方法启动项目试试 应该没有报错 如果报错就检查下你的数据库链接配置对不对
建立mvc的包结构 我建立了 controller service entity 和dao来演示
由于我们知道SpringBoot自动装配原理中,有一条是@SpringBootApplication下有个包扫描注解 是默认扫描启动类所在目录及以下的Spring注解,所以不要建错位置。 会导致无法自动装配 (当然会的同学也可以自己配置扫描位置)
下一步
用Database插件 链接数据库 逆向生成实体类 到entity包下
我们可以使用@Data注解来配置get set等方法来简化 实体类的内容
同时加上@ManagedBean 标明这是一个受管bean
定义数据库操作接口
类似mybatis的mapper接口一样,包含操作数据库的方法,注入到service层使用,这里用的jpa,继承 JpaRepository 类
JpaRepository 的子类已经实现了简单的增删改查的方法,我们也可以自定义HQL的方法
package com.jpa.springbootjpademo.dao; import com.jpa.springbootjpademo.entity.UserinfoEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; // hibernate的接口,springboot整合hibernate用的是jpa,接口要集成JpaRepository // 里面已经集成了几个方法,额外的查询需要我们手动添加方法HQL public interface UserinfoRepository extends JpaRepository<UserinfoEntity,Integer> { // 这个在集成的类的子类里面有明确的sql实现,不用再写SQL或者HQL,也可以不写,直接在service里用子类的 //@Query(value = "SELECT u FROM userinfo u WHERE username=:name") // 这是HQL :xx 指传入参数,跟下面注解@Param对应 @Query(value = "SELECT * FROM userinfo WHERE username=?", nativeQuery = true) // 这是SQL nativeQuery为true代表使用SQL语言 UserinfoEntity findByName(@Param("name") String name); }
service
package com.jpa.springbootjpademo.service; import com.jpa.springbootjpademo.dao.UserinfoRepository; import com.jpa.springbootjpademo.entity.UserinfoEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserinfoService { @Autowired private UserinfoRepository userinfoRepository; public List<UserinfoEntity> findAll(){ return userinfoRepository.findAll(); } public UserinfoEntity findByName(String name){ return userinfoRepository.findByName(name); } //新增、修改 这里 根据主键插入 其他值 如果主键不是整型id 会报错 注意按需求自己实现插入方法即可 public void save(UserinfoEntity user){ userinfoRepository.save(user); } }
测试JPA
在测试包下新建测试类 书写单元测试方法
package com.jpa.springbootjpademo; import com.jpa.springbootjpademo.dao.UserinfoRepository; import com.jpa.springbootjpademo.entity.UserinfoEntity; import com.jpa.springbootjpademo.service.UserinfoService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @SpringBootTest @RunWith(SpringRunner.class) public class SpringBootJpaDemoApplicationTests { @Autowired private UserinfoRepository userinfoRepository; @Autowired private UserinfoService userinfoService; @Test public void myTest() { List<UserinfoEntity> all = userinfoService.findAll(); System.out.println(all); } @Test public void myTest1() { List<UserinfoEntity> all = userinfoRepository.findAll(); System.out.println(all); } }
运行测试类后jpa正常使用
SpringBoot启动类配置
package com.jpa.springbootjpademo; import com.sun.faces.config.ConfigureListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.faces.webapp.FacesServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; @SpringBootApplication public class SpringBootJpaDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootJpaDemoApplication.class, args); } @Bean public FacesServlet facesServlet() { return new FacesServlet(); } @Bean public ServletRegistrationBean facesServletRegistration() { ServletRegistrationBean registration = new ServletRegistrationBean(facesServlet(), new String[] {"*.xhtml" }); registration.setName("FacesServlet"); registration.setLoadOnStartup(1); return registration; } @Configuration static class ConfigureJSFContextParameters implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration","true"); servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX",".xhtml"); servletContext.setInitParameter("encoding","UTF-8"); } } @Bean public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() { return new ServletListenerRegistrationBean<ConfigureListener>(new ConfigureListener()); } }
现在我们测试jsf
首先书写一个xhtml文件 放到webapp目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core"> <f:view> <h:outputLabel value="Hello, world"/> </f:view> </html>
启动项目 访问