1、新建maven web项目
pom.xml 添加以下依赖项,
spring-core、spring-context、spring-web、spring-webmvc、mysql-connector-java、
spring-data-jpa、spring-orm、spring-data-commons、hibernate-core、
hibernate-entitymanager、hibernate-jpa-2.1-api
2、META-INF文件夹下添加context.xml
配置JNDI数据源
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
auth="Container"
driverClassName="com.mysql.cj.jdbc.Driver"
maxIdle="30"
maxTotal="50"
maxWaitMillis="-1"
name="jdbc/TestDB"
username="username"
password="passwd"
type="javax.sql.DataSource"
url="jdbc:mysql://192.168.1.102/dbname?serverTimezone=UTC"/>
</Context>
3、配置tomcat启动时初始化springmvc的初始类
package packagename;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebmvcAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
4、WebConfig和RootConfig类
package packagename;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("packagename.controller")
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver cnViewResolver(ContentNegotiationManager cnm) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
package packagename.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableJpaRepositories(basePackages = "packagename.repository")
@ComponentScan(basePackages = { "packagename.domainmodel,packagename.service,"
+ "packagename.repository" })
@ImportResource("classpath:dataSource.xml") //配置JNDI数据源
public class RootConfig {
private Map<String, ?> jpaProperties() {
Map<String, String> jpaPropertiesMap = new HashMap<String, String>();
jpaPropertiesMap.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
jpaPropertiesMap.put("hibernate.hbm2ddl.auto", "create");
jpaPropertiesMap.put("hibernate.show_sql", "true");
jpaPropertiesMap.put("hibernate.format_sql", "true");
return jpaPropertiesMap;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Autowired DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
emfb.setDataSource(dataSource);
emfb.setPackagesToScan("packagename.domainmodel");
emfb.setJpaPropertyMap(jpaProperties());
return emfb;
}
@Bean
@Autowired
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
5、配置JNDI数据源
在类路径下新建dataSource.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:jee="http://www.springframework.org/schema/jee"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jee
https://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/websocket
https://www.springframework.org/schema/websocket/spring-websocket.xsd"
>
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/TestDB" resource-ref="true"/>
</beans>
6、新建实体类
package packagename.domainmodel;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue
protected long id;
private String user_name;
private String user_pass;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_pass() {
return user_pass;
}
public void setUser_pass(String user_pass) {
this.user_pass = user_pass;
}
}
7、新建实体仓库类
package packagename.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import cn.yanglu.web.testdynamicjavaweb.domainmodel.User;
public interface RegisterReposi extends JpaRepository<User,Long> {
}