diff --git a/core/src/main/java/core/aop/Advisor.java b/core/src/main/java/core/aop/Advisor.java index 546ba39..82a5dc9 100644 --- a/core/src/main/java/core/aop/Advisor.java +++ b/core/src/main/java/core/aop/Advisor.java @@ -1,7 +1,6 @@ package core.aop; -import core.dao.BaseDao1; -import core.dao.BaseDao2; +import core.service.BaseService; import org.aopalliance.aop.Advice; import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; import org.springframework.stereotype.Component; @@ -20,7 +19,7 @@ public class Advisor extends StaticMethodMatcherPointcutAdvisor { @Override public boolean matches(Method method, Class aClass) { - return BaseDao1.class.isAssignableFrom(aClass)||BaseDao2.class.isAssignableFrom(aClass); + return BaseService.class.isAssignableFrom(aClass); } @PostConstruct diff --git a/core/src/main/java/core/dao/BaseDao1.java b/core/src/main/java/core/dao/BaseDao1.java deleted file mode 100644 index 2c5a93c..0000000 --- a/core/src/main/java/core/dao/BaseDao1.java +++ /dev/null @@ -1,23 +0,0 @@ -package core.dao; - -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.orm.hibernate5.HibernateTemplate; -import org.springframework.stereotype.Repository; - -/** - * Created by reborn on 2017/7/31. - */ - -@Repository -public class BaseDao1 extends HibernateTemplate{ - - @Autowired - public BaseDao1(SessionFactory aliyun) { - super(aliyun); - } - - - - -} diff --git a/core/src/main/java/core/dao/BaseDao2.java b/core/src/main/java/core/dao/BaseDao2.java deleted file mode 100644 index a455208..0000000 --- a/core/src/main/java/core/dao/BaseDao2.java +++ /dev/null @@ -1,26 +0,0 @@ -package core.dao; - -import db.AbstractModel; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.orm.hibernate5.HibernateTemplate; -import org.springframework.stereotype.Repository; - -import java.io.Serializable; - -@Repository -public class BaseDao2 extends HibernateTemplate { - - @Autowired - public BaseDao2(SessionFactory huaWeiCloud) { - super(huaWeiCloud); - } - - public void delete(Class tClass, Serializable key) throws DataAccessException { - T model = load(tClass, key); - if (model != null) { - delete(model); - } - } -} diff --git a/core/src/main/java/core/service/BaseService.java b/core/src/main/java/core/service/BaseService.java index 4c6bd39..39cfae7 100644 --- a/core/src/main/java/core/service/BaseService.java +++ b/core/src/main/java/core/service/BaseService.java @@ -1,45 +1,38 @@ package core.service; -import core.dao.BaseDao1; -import core.dao.BaseDao2; import db.AbstractModel; import db.DBAction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.hibernate.criterion.DetachedCriteria; +import org.hibernate.criterion.Projections; import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; +import org.springframework.orm.hibernate5.HibernateTemplate; -import javax.annotation.Resource; import java.util.List; /** * Created by reborn on 2017/7/28. */ -@Service -public class BaseService { +public abstract class BaseService { protected static Logger log=LogManager.getLogger(); - @Resource - protected BaseDao1 baseDao1; - @Resource - protected BaseDao2 baseDao2; + protected abstract HibernateTemplate getHibernateTemplate() ; - @Transactional("transactionManager1") public T curd(DBAction action, T command) throws DataAccessException { switch (action) { case C: - baseDao1.save(command);break; + getHibernateTemplate().save(command);break; case U: - baseDao1.update(command);break; + getHibernateTemplate().update(command);break; case R: - AbstractModel model=baseDao1.get(command.getClass(), command.primaryKey()); + AbstractModel model=getHibernateTemplate().get(command.getClass(), command.primaryKey()); if(model!=null){ return model.cast(); } case D: - baseDao1.delete(command);break; + getHibernateTemplate().delete(command);break; default: throw new RuntimeException("非法操作:" + action); } @@ -48,9 +41,11 @@ public class BaseService { } public List find(T command, int firstResult, int maxResults){ - return baseDao1.findByCriteria(command.getCriteria(),firstResult,maxResults); + return getHibernateTemplate().findByCriteria(command.getCriteria(),firstResult,maxResults); } - + public Long rowCount(Class tClass){ + return getHibernateTemplate().executeWithNativeSession(session -> (Long) DetachedCriteria.forClass(tClass).setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult()); + } } diff --git a/db/src/main/java/db/AbstractModel.java b/db/src/main/java/db/AbstractModel.java index a493dda..34d5bb4 100644 --- a/db/src/main/java/db/AbstractModel.java +++ b/db/src/main/java/db/AbstractModel.java @@ -9,7 +9,7 @@ import java.io.Serializable; * Created by reborn on 2017/8/3. */ -public abstract class AbstractModel{ +public abstract class AbstractModel extends ToJSON{ public abstract Serializable primaryKey(); diff --git a/db/src/main/java/db/JsonResult.java b/db/src/main/java/db/JsonResult.java index 8fe1f79..d6653f2 100644 --- a/db/src/main/java/db/JsonResult.java +++ b/db/src/main/java/db/JsonResult.java @@ -1,40 +1,24 @@ package db; -import java.io.Serializable; - public class JsonResult extends ToJSON{ private T data; - private JsonResult.type type; + private Type type; private DBAction action; - public JsonResult(T data, JsonResult.type type, DBAction action) { + public JsonResult(T data, Type type, DBAction action) { this.data = data; this.type = type; this.action = action; } - public enum type implements Serializable { - success("成功"), - fail("失败") ; - private String desc; - - type(String desc) { - this.desc = desc; - } - - public String getDesc() { - return desc; - } - } - public T getData() { return data; } - public JsonResult.type getType() { + public Type getType() { return type; } diff --git a/db/src/main/java/db/PageResult.java b/db/src/main/java/db/PageResult.java new file mode 100644 index 0000000..4b6a6c4 --- /dev/null +++ b/db/src/main/java/db/PageResult.java @@ -0,0 +1,69 @@ +package db; + +import java.util.List; + +public class PageResult { + private long count; + + private int currentPage; + + private List datas; + + private int pageSize; + + private long pages; + + private Type type; + + private String errorMsg; + + /** + * + * @param count 总行数 + * @param currentPage 当前分页数 + * @param datas 数据 + * @param pageSize 分页大小 + * @param type 操作结果 + */ + public PageResult(long count, int currentPage, List datas, int pageSize, Type type) { + this.count = count; + this.currentPage = currentPage+1; + this.datas = datas; + this.pageSize = pageSize; + this.pages=count%pageSize==0?count/pageSize:count/pageSize+1; + this.type = type; + } + + public PageResult(Type type, String errorMsg) { + this.type = type; + this.errorMsg = errorMsg; + } + + public long getCount() { + return count; + } + + public int getCurrentPage() { + return currentPage; + } + + public List getDatas() { + return datas; + } + + public Type getType() { + return type; + } + + public int getPageSize() { + return pageSize; + } + + public long getPages() { + return pages; + } + + public String getErrorMsg() { + return errorMsg; + } +} diff --git a/db/src/main/java/db/ToJSON.java b/db/src/main/java/db/ToJSON.java index aa4dc2e..9f31b66 100644 --- a/db/src/main/java/db/ToJSON.java +++ b/db/src/main/java/db/ToJSON.java @@ -12,7 +12,11 @@ public class ToJSON { private static Logger log=LogManager.getLogger(); - protected void init(){ + static { + init(); + } + + protected static void init(){ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.enable(SerializationFeature.INDENT_OUTPUT); } diff --git a/db/src/main/java/db/Type.java b/db/src/main/java/db/Type.java new file mode 100644 index 0000000..ceb8a57 --- /dev/null +++ b/db/src/main/java/db/Type.java @@ -0,0 +1,17 @@ +package db; + +import java.io.Serializable; + +public enum Type implements Serializable { + success("成功"), + fail("失败") ; + private String desc; + + Type(String desc) { + this.desc = desc; + } + + public String getDesc() { + return desc; + } +} diff --git a/db/src/main/java/db/annotation/BiliBili.java b/db/src/main/java/db/annotation/BiliBili.java new file mode 100644 index 0000000..74e3eb4 --- /dev/null +++ b/db/src/main/java/db/annotation/BiliBili.java @@ -0,0 +1,4 @@ +package db.annotation; + +public @interface BiliBili { +} diff --git a/db/src/main/java/db/config/AddConfig.java b/db/src/main/java/db/config/AddConfig.java new file mode 100644 index 0000000..f9f7ae2 --- /dev/null +++ b/db/src/main/java/db/config/AddConfig.java @@ -0,0 +1,7 @@ +package db.config; + +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; + +public interface AddConfig { + void addConfig(LocalSessionFactoryBean bean); +} diff --git a/db/src/main/java/db/config/HibernateConfig.java b/db/src/main/java/db/config/HibernateConfig.java index b1cbf59..185f95c 100644 --- a/db/src/main/java/db/config/HibernateConfig.java +++ b/db/src/main/java/db/config/HibernateConfig.java @@ -1,129 +1,192 @@ package db.config; import com.alibaba.druid.pool.DruidDataSource; +import db.AbstractModel; +import db.model.DataSourceModel; +import db.util.ClassScaner; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import javax.annotation.PostConstruct; +import javax.annotation.Resource; import javax.sql.DataSource; import java.io.IOException; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import java.util.Properties; +import java.util.*; /** * Created by reborn on 2017/7/28. */ -public class HibernateConfig{ +public class HibernateConfig { - private static Logger log=LogManager.getLogger(); + private static Logger log = LogManager.getLogger(); @Value("${hibernate.dialect}") private String dialect; @Value("${hibernate.connection.driver_class}") private String driver; - @Value("${hibernate.connection.url}") + @Value("${db_url}") private String url; - @Value("${hibernate.connection.username}") + @Value("${db_username}") private String username; - @Value("${hibernate.connection.password}") + @Value("${db_password}") private String password; - @Value("${hibernate.connection.url2}") - private String url2; - @Value("${hibernate.connection.username2}") - private String username2; - @Value("${hibernate.connection.password2}") - private String password2; + @Resource + private DefaultListableBeanFactory beanFactory; - @Value("${sessionFactory.scan}") - private String packagesToScan[]; + private static final String rootKey = "ROOT"; - private static final String tableNote="tableNote"; + private static final String tableNote = "tableNote"; - private LocalSessionFactoryBean aliyun = new LocalSessionFactoryBean(); + private static final Class rootClass = DataSourceModel.class; - private LocalSessionFactoryBean huaWeiCloud = new LocalSessionFactoryBean(); + private static final String annotation = "db.annotation."; - private DruidDataSource dataSource(String url,String username,String password){ - DruidDataSource dataSource=new DruidDataSource(); + private static final String basePackage = "db.model"; + + private static final Map map = new HashMap<>(); + + public static final HibernateTemplate get(String key) { + return map.get(key); + } + + public static final Map get(){ + return map; + } + + private DruidDataSource dataSource(String url, String username, String password) { + DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driver); - log.info("数据源初始化\nurl="+url+"\nusername="+username+"\npassword="+password); + log.info("数据源初始化\nurl=" + url + "\nusername=" + username + "\npassword=" + password); return dataSource; } + private DruidDataSource dataSource(DataSourceModel dataSourceModel) { + String url = "jdbc:mysql://" + dataSourceModel.getHostname() + ":" + dataSourceModel.getDbPort() + "/" + dataSourceModel.getDbName() + "?serverTimezone=UTC&useSSL=false"; + return dataSource(url, dataSourceModel.getUsername(), dataSourceModel.getDbPassword()); + } - - @PostConstruct - private void init() { - initSessionFactory(aliyun,dataSource(url,username,password)); - initSessionFactory(huaWeiCloud,dataSource(url2,username2,password2)); + private HibernateTemplate initRootDB() { + SessionFactory rootdb_sessionFactory = initSessionFactory(dataSource(url, username, password), (LocalSessionFactoryBean bean) -> { + bean.setAnnotatedClasses(rootClass); + }); + return new HibernateTemplate(rootdb_sessionFactory); } - private void initSessionFactory(LocalSessionFactoryBean bean, DataSource dataSource){ - Properties properties=new Properties(); - properties.setProperty("hibernate.dialect",dialect); - properties.setProperty("hibernate.format_sql","true"); - bean.setHibernateProperties(properties); - bean.setDataSource(dataSource); - bean.setPackagesToScan(packagesToScan); - try { - bean.afterPropertiesSet(); - checkClass(bean); - } catch (IOException e) { - e.printStackTrace(); + private HibernateTemplate initDB(DataSourceModel dataSourceModel) { + SessionFactory sessionFactory = initSessionFactory(dataSource(dataSourceModel), (LocalSessionFactoryBean bean) -> { + Set classes; + + Class c; + try { + c = Class.forName(annotation + dataSourceModel.getAnnotation()); + } catch (ClassNotFoundException e) { + return; + } + + if (Annotation.class.isAssignableFrom(c)) { + classes = ClassScaner.scan(basePackage, (Class) c); + bean.setAnnotatedClasses(classes.toArray(new Class[classes.size()])); + } else { + log.error(c+"不是注解!!!"); + } + }); + + if (sessionFactory != null) { + HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(); + hibernateTransactionManager.setSessionFactory(sessionFactory); + beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbDesc(),DBBeanNameManager.transactionManager),hibernateTransactionManager); + return new HibernateTemplate(sessionFactory); + } else { + return null; } } - @Bean("aliyun") - public SessionFactory aliyun(){ - return aliyun.getObject(); - } + public enum DBBeanNameManager { + hibernateTemplate, + transactionManager; + public static String getName(String key,DBBeanNameManager type){ + return type.name()+"_"+key; + } - @Bean("huaWeiCloud") - public SessionFactory huaWeiCloud(){ - return huaWeiCloud.getObject(); + public static String getName(DBBeanNameManager type){ + return type.name()+"_root"; + } } - @Bean("transactionManager1") - public HibernateTransactionManager aliyunTransaction() { - HibernateTransactionManager hibernateTransactionManager=new HibernateTransactionManager(); - hibernateTransactionManager.setSessionFactory(aliyun()); - return hibernateTransactionManager; + @PostConstruct + private void init() { + + HibernateTemplate root = initRootDB(); + beanFactory.registerSingleton(DBBeanNameManager.getName(DBBeanNameManager.hibernateTemplate),root); + map.put(rootKey, root); + + List dataSourceModels = root.loadAll(rootClass); + for (DataSourceModel dataSourceModel : dataSourceModels) { + HibernateTemplate hibernateTemplate = initDB(dataSourceModel); + if (hibernateTemplate != null) { + beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbDesc(),DBBeanNameManager.hibernateTemplate),hibernateTemplate); + map.put(dataSourceModel.getDbDesc(), hibernateTemplate); + } + } + } - @Bean("transactionManager2") - public HibernateTransactionManager huaweiTransaction() { - HibernateTransactionManager hibernateTransactionManager=new HibernateTransactionManager(); - hibernateTransactionManager.setSessionFactory(huaWeiCloud()); - return hibernateTransactionManager; + + private SessionFactory initSessionFactory(DataSource dataSource, AddConfig config) { + LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); + Properties properties = new Properties(); + properties.setProperty("hibernate.dialect", dialect); + properties.setProperty("hibernate.format_sql", "true"); + bean.setHibernateProperties(properties); + bean.setDataSource(dataSource); + try { + config.addConfig(bean); + bean.afterPropertiesSet(); + checkClass(bean); + return bean.getObject(); + } catch (IOException e) { + log.error(e); + } + return null; } - private void checkClass(LocalSessionFactoryBean bean){ - for(Class c:bean.getMetadataSources().getAnnotatedClasses()){ - try { - Method method=ReflectionUtils.findMethod(c,tableNote); - Object result=ReflectionUtils.invokeMethod(method,c.newInstance()); - if(ObjectUtils.isEmpty(result)){ - throw new RuntimeException(method+"没有正确重写"); + private void checkClass(LocalSessionFactoryBean bean) { + for (Class c : bean.getMetadataSources().getAnnotatedClasses()) { + if (AbstractModel.class.isAssignableFrom(c)) { + try { + Method method = ReflectionUtils.findMethod(c, tableNote); + Object result = ReflectionUtils.invokeMethod(method, c.newInstance()); + if (ObjectUtils.isEmpty(result)) { + throw new RuntimeException(method + "没有正确重写"); + }else{ + log.info("扫描实体类:"+c+",映射表:"+result); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); + } else { + log.error(c + "没有继承" + AbstractModel.class); } } + } diff --git a/db/src/main/java/db/model/DataSourceModel.java b/db/src/main/java/db/model/DataSourceModel.java new file mode 100644 index 0000000..7e3bf83 --- /dev/null +++ b/db/src/main/java/db/model/DataSourceModel.java @@ -0,0 +1,119 @@ +package db.model; + +import db.AbstractModel; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table(name = "datasource", schema = "rootdb", catalog = "") +public class DataSourceModel extends AbstractModel { + private String dbDesc; + private String hostname; + private int dbPort; + private String username; + private String dbPassword; + private String dbName; + private String annotation; + + @Id + @Column(name = "db_desc", nullable = false, length = 10) + public String getDbDesc() { + return dbDesc; + } + + public void setDbDesc(String dbDesc) { + this.dbDesc = dbDesc; + } + + @Basic + @Column(name = "hostname", nullable = false, length = 32) + public String getHostname() { + return hostname; + } + + public void setHostname(String hostname) { + this.hostname = hostname; + } + + @Basic + @Column(name = "db_port", nullable = false) + public int getDbPort() { + return dbPort; + } + + public void setDbPort(int dbPort) { + this.dbPort = dbPort; + } + + @Basic + @Column(name = "username", nullable = false, length = 10) + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Basic + @Column(name = "db_password", nullable = false, length = 10) + public String getDbPassword() { + return dbPassword; + } + + public void setDbPassword(String dbPassword) { + this.dbPassword = dbPassword; + } + + @Basic + @Column(name = "db_name", nullable = false, length = 10) + public String getDbName() { + return dbName; + } + + public void setDbName(String dbName) { + this.dbName = dbName; + } + + @Basic + @Column(name = "annotation", nullable = true, length = 10) + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DataSourceModel that = (DataSourceModel) o; + return dbPort == that.dbPort && + Objects.equals(dbDesc, that.dbDesc) && + Objects.equals(hostname, that.hostname) && + Objects.equals(username, that.username) && + Objects.equals(dbPassword, that.dbPassword) && + Objects.equals(dbName, that.dbName) && + Objects.equals(annotation, that.annotation); + } + + @Override + public int hashCode() { + + return Objects.hash(dbDesc, hostname, dbPort, username, dbPassword, dbName, annotation); + } + + @Override + public Serializable primaryKey() { + return getDbDesc(); + } + + @Override + public String tableNote() { + return "数据源"; + } +} diff --git a/db/src/main/java/db/model/CidEntity.java b/db/src/main/java/db/model/bilibili/CidEntity.java similarity index 99% rename from db/src/main/java/db/model/CidEntity.java rename to db/src/main/java/db/model/bilibili/CidEntity.java index a6373a7..174ddbe 100644 --- a/db/src/main/java/db/model/CidEntity.java +++ b/db/src/main/java/db/model/bilibili/CidEntity.java @@ -1,4 +1,4 @@ -package db.model; +package db.model.bilibili; import db.AbstractModel; diff --git a/db/src/main/java/db/model/DataModel.java b/db/src/main/java/db/model/bilibili/DataModel.java similarity index 99% rename from db/src/main/java/db/model/DataModel.java rename to db/src/main/java/db/model/bilibili/DataModel.java index 8ad789f..0596400 100644 --- a/db/src/main/java/db/model/DataModel.java +++ b/db/src/main/java/db/model/bilibili/DataModel.java @@ -1,11 +1,13 @@ -package db.model; +package db.model.bilibili; import db.AbstractModel; +import db.annotation.BiliBili; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; +@BiliBili @Entity @Table(name = "data", schema = "bilibili", catalog = "bilibili") public class DataModel extends AbstractModel { diff --git a/db/src/main/java/db/model/MenuModel.java b/db/src/main/java/db/model/bilibili/MenuModel.java similarity index 96% rename from db/src/main/java/db/model/MenuModel.java rename to db/src/main/java/db/model/bilibili/MenuModel.java index 0370aef..08e25fb 100644 --- a/db/src/main/java/db/model/MenuModel.java +++ b/db/src/main/java/db/model/bilibili/MenuModel.java @@ -1,6 +1,7 @@ -package db.model; +package db.model.bilibili; import db.AbstractModel; +import db.annotation.BiliBili; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Property; @@ -10,6 +11,7 @@ import java.io.Serializable; import java.util.List; import java.util.Objects; +@BiliBili @Entity @Table(name = "menu", schema = "bilibili", catalog = "bilibili") public class MenuModel extends AbstractModel { @@ -87,7 +89,7 @@ public class MenuModel extends AbstractModel { @Override public String tableNote() { - return "测试表"; + return "菜单表"; } @Basic diff --git a/db/src/main/java/db/model/ScheduledTaskEntity.java b/db/src/main/java/db/model/bilibili/ScheduledTaskEntity.java similarity index 99% rename from db/src/main/java/db/model/ScheduledTaskEntity.java rename to db/src/main/java/db/model/bilibili/ScheduledTaskEntity.java index e17ca51..4309e2d 100644 --- a/db/src/main/java/db/model/ScheduledTaskEntity.java +++ b/db/src/main/java/db/model/bilibili/ScheduledTaskEntity.java @@ -1,4 +1,4 @@ -package db.model; +package db.model.bilibili; import db.AbstractModel; diff --git a/db/src/main/java/db/model/TaskEntity.java b/db/src/main/java/db/model/bilibili/TaskEntity.java similarity index 97% rename from db/src/main/java/db/model/TaskEntity.java rename to db/src/main/java/db/model/bilibili/TaskEntity.java index fb02f26..10d0dad 100644 --- a/db/src/main/java/db/model/TaskEntity.java +++ b/db/src/main/java/db/model/bilibili/TaskEntity.java @@ -1,4 +1,4 @@ -package db.model; +package db.model.bilibili; import db.AbstractModel; diff --git a/db/src/main/java/db/util/ClassScaner.java b/db/src/main/java/db/util/ClassScaner.java new file mode 100644 index 0000000..9bcee1a --- /dev/null +++ b/db/src/main/java/db/util/ClassScaner.java @@ -0,0 +1,124 @@ +package db.util; + +import org.apache.commons.lang3.ArrayUtils; +import org.springframework.beans.factory.BeanDefinitionStoreException; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternUtils; +import org.springframework.core.type.classreading.CachingMetadataReaderFactory; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.core.type.filter.TypeFilter; +import org.springframework.util.StringUtils; +import org.springframework.util.SystemPropertyUtils; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +public class ClassScaner implements ResourceLoaderAware { + //保存过滤规则要排除的注解 + private final List includeFilters = new LinkedList(); + private final List excludeFilters = new LinkedList(); + + private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver); + + public static Set scan(String[] basePackages, + Class... annotations) { + ClassScaner cs = new ClassScaner(); + + if(ArrayUtils.isNotEmpty(annotations)) { + for (Class anno : annotations) { + cs.addIncludeFilter(new AnnotationTypeFilter(anno)); + } + } + + Set classes = new HashSet(); + for (String s : basePackages) + classes.addAll(cs.doScan(s)); + return classes; + } + + public static Set scan(String basePackages, Class... annotations) { + return ClassScaner.scan(StringUtils.tokenizeToStringArray(basePackages, ",; \t\n"), annotations); + } + + public final ResourceLoader getResourceLoader() { + return this.resourcePatternResolver; + } + + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourcePatternResolver = ResourcePatternUtils + .getResourcePatternResolver(resourceLoader); + this.metadataReaderFactory = new CachingMetadataReaderFactory( + resourceLoader); + } + + public void addIncludeFilter(TypeFilter includeFilter) { + this.includeFilters.add(includeFilter); + } + + public void addExcludeFilter(TypeFilter excludeFilter) { + this.excludeFilters.add(0, excludeFilter); + } + + public void resetFilters(boolean useDefaultFilters) { + this.includeFilters.clear(); + this.excludeFilters.clear(); + } + + public Set doScan(String basePackage) { + Set classes = new HashSet(); + try { + String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + + org.springframework.util.ClassUtils + .convertClassNameToResourcePath(SystemPropertyUtils + .resolvePlaceholders(basePackage)) + + "/**/*.class"; + Resource[] resources = this.resourcePatternResolver + .getResources(packageSearchPath); + + for (int i = 0; i < resources.length; i++) { + Resource resource = resources[i]; + if (resource.isReadable()) { + MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); + if ((includeFilters.size() == 0 && excludeFilters.size() == 0) + || matches(metadataReader)) { + try { + classes.add(Class.forName(metadataReader + .getClassMetadata().getClassName())); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } + } catch (IOException ex) { + throw new BeanDefinitionStoreException( + "I/O failure during classpath scanning", ex); + } + return classes; + } + + protected boolean matches(MetadataReader metadataReader) throws IOException { + for (TypeFilter tf : this.excludeFilters) { + if (tf.match(metadataReader, this.metadataReaderFactory)) { + return false; + } + } + for (TypeFilter tf : this.includeFilters) { + if (tf.match(metadataReader, this.metadataReaderFactory)) { + return true; + } + } + return false; + } +} diff --git a/web/src/main/java/web/config/AppConfig.java b/web/src/main/java/web/config/AppConfig.java index 802550e..b121dc6 100644 --- a/web/src/main/java/web/config/AppConfig.java +++ b/web/src/main/java/web/config/AppConfig.java @@ -11,4 +11,5 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @ComponentScan({"core"}) @Import(HibernateConfig.class) public class AppConfig { + } diff --git a/web/src/main/java/web/config/SpringConfig.java b/web/src/main/java/web/config/SpringConfig.java index f39e4d2..93caafa 100644 --- a/web/src/main/java/web/config/SpringConfig.java +++ b/web/src/main/java/web/config/SpringConfig.java @@ -1,30 +1,32 @@ package web.config; -import core.dao.BaseDao1; +import db.config.HibernateConfig; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor; import org.springframework.web.servlet.config.annotation.*; import javax.annotation.Resource; import java.util.List; +import java.util.Map; /** * Created by reborn on 2017/7/28. */ @Configuration @EnableWebMvc -@PropertySource("classpath:config.properties") -@ComponentScan({"web.controller","web.service"}) +@PropertySource({"classpath:config.properties"}) +@ComponentScan({"web.controller","web.service","web.util"}) public class SpringConfig implements WebMvcConfigurer { - @Resource - private BaseDao1 baseDao; + private DefaultListableBeanFactory beanFactory; @Override public void configureViewResolvers(ViewResolverRegistry registry) { @@ -40,9 +42,13 @@ public class SpringConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { - OpenSessionInViewInterceptor interceptor=new OpenSessionInViewInterceptor(); - interceptor.setSessionFactory(baseDao.getSessionFactory()); - registry.addWebRequestInterceptor(interceptor); + Map hibernateTemplateMap= HibernateConfig.get(); + for(String key:hibernateTemplateMap.keySet()) { + OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); + interceptor.setSessionFactory(hibernateTemplateMap.get(key).getSessionFactory()); + registry.addWebRequestInterceptor(interceptor); + } + } @Override @@ -51,4 +57,6 @@ public class SpringConfig implements WebMvcConfigurer { builder.indentOutput(true); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); } + + } diff --git a/web/src/main/java/web/controller/AdminController.java b/web/src/main/java/web/controller/AdminController.java index a2590ef..faee02c 100644 --- a/web/src/main/java/web/controller/AdminController.java +++ b/web/src/main/java/web/controller/AdminController.java @@ -2,7 +2,9 @@ package web.controller; import db.DBAction; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; +import web.html.ElementId; import javax.servlet.http.HttpServletRequest; @@ -10,11 +12,12 @@ import javax.servlet.http.HttpServletRequest; * Created by reborn on 2017/9/14. */ @Controller -public class AdminController extends BaseController{ +public class AdminController extends BiliController{ @RequestMapping("index") - private String index(HttpServletRequest request){ + private String index(HttpServletRequest request,Model model){ log.info("进入首页"); + model.addAttribute("elementPreifx",ElementId.getAll()); return "index"; } diff --git a/web/src/main/java/web/controller/BaseController.java b/web/src/main/java/web/controller/BaseController.java index 567f8f2..8ee9a3d 100644 --- a/web/src/main/java/web/controller/BaseController.java +++ b/web/src/main/java/web/controller/BaseController.java @@ -4,6 +4,7 @@ import core.service.BaseService; import db.AbstractModel; import db.DBAction; import db.JsonResult; +import db.Type; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.dao.DataAccessException; @@ -13,16 +14,15 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import javax.annotation.Resource; - /** * Created by reborn on 2017/9/14. */ -public abstract class BaseController{ +public abstract class BaseController{ protected static Logger log=LogManager.getLogger(); - @Resource - public BaseService baseService; + protected E service; + + protected abstract void setService(E service); @ResponseBody @RequestMapping(value = "{action}", produces = MediaType.APPLICATION_JSON_VALUE) @@ -30,13 +30,13 @@ public abstract class BaseController{ log.info(model.tableNote()+ "进行" + action.getCh() + "操作请求"); if(checkAction(action)) { try { - return new JsonResult(baseService.curd(action, model),JsonResult.type.success,action); + return new JsonResult<>(service.curd(action, model), Type.success, action); }catch (DataAccessException e){ log.error(e); - return new JsonResult("非法操作",JsonResult.type.fail,action); + return new JsonResult<>("非法操作", Type.fail, action); } }else{ - return new JsonResult<>(model.tableNote() + "不允许" + action.getCh() + "操作", JsonResult.type.fail,action); + return new JsonResult<>(model.tableNote() + "不允许" + action.getCh() + "操作", Type.fail,action); } } @@ -47,17 +47,17 @@ public abstract class BaseController{ log.info(queryCommand.tableNote()+ "进行批量" + action.getCh() + "操作请求"); if(checkAction(action)) { try { - return new JsonResult<>(baseService.find(queryCommand, firstResult, maxResults), JsonResult.type.success, action); + return new JsonResult<>(service.find(queryCommand, firstResult, maxResults), Type.success, action); } catch (DataAccessException e) { log.error(e); - return new JsonResult("非法操作",JsonResult.type.fail,action); + return new JsonResult<>("非法操作", Type.fail, action); } }else{ - return new JsonResult<>(queryCommand.tableNote() + "不允许" + action.getCh() + "操作", JsonResult.type.fail,action); + return new JsonResult<>(queryCommand.tableNote() + "不允许" + action.getCh() + "操作", Type.fail,action); } } - public abstract boolean checkAction(DBAction action); + protected abstract boolean checkAction(DBAction action); } diff --git a/web/src/main/java/web/controller/BiliController.java b/web/src/main/java/web/controller/BiliController.java new file mode 100644 index 0000000..b9fccb8 --- /dev/null +++ b/web/src/main/java/web/controller/BiliController.java @@ -0,0 +1,20 @@ +package web.controller; + +import db.AbstractModel; +import db.DBAction; +import org.springframework.beans.factory.annotation.Autowired; +import web.service.BiliService; + +public class BiliController extends BaseController{ + + @Override + @Autowired + protected void setService(BiliService service) { + this.service=service; + } + + @Override + protected boolean checkAction(DBAction action) { + return false; + } +} diff --git a/web/src/main/java/web/controller/CommentController.java b/web/src/main/java/web/controller/CommentController.java deleted file mode 100644 index 8c4bb65..0000000 --- a/web/src/main/java/web/controller/CommentController.java +++ /dev/null @@ -1,18 +0,0 @@ -package web.controller; - -import db.DBAction; -import db.model.DataModel; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping("/comment") -public class CommentController extends BaseController{ - - - - @Override - public boolean checkAction(DBAction action) { - return true; - } -} diff --git a/web/src/main/java/web/controller/DataController.java b/web/src/main/java/web/controller/DataController.java index 59ce081..925f4ca 100644 --- a/web/src/main/java/web/controller/DataController.java +++ b/web/src/main/java/web/controller/DataController.java @@ -1,8 +1,11 @@ package web.controller; +import db.AbstractModel; import db.DBAction; -import db.model.DataModel; +import db.model.bilibili.DataModel; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import web.service.DataService; @@ -12,11 +15,16 @@ import java.util.EnumSet; @Controller @RequestMapping("/data") -public class DataController extends BaseController { +public class DataController extends TableController { @Resource private DataService dataService; + @RequestMapping + public String find(Model model, DataModel queryCommand){ + return super.find(model,queryCommand,0,10); + } + @RequestMapping("start/{size}") public void start(@PathVariable Integer size){ stop(); @@ -28,6 +36,12 @@ public class DataController extends BaseController { dataService.stop(); } + @Override + @Autowired + protected void setService(DataService service) { + this.service=service; + } + @Override public boolean checkAction(DBAction action) { return !EnumSet.of(DBAction.D).contains(action); diff --git a/web/src/main/java/web/controller/MenuController.java b/web/src/main/java/web/controller/MenuController.java index ec900b9..35971c5 100644 --- a/web/src/main/java/web/controller/MenuController.java +++ b/web/src/main/java/web/controller/MenuController.java @@ -2,7 +2,7 @@ package web.controller; import db.AbstractModel; import db.DBAction; -import db.model.MenuModel; +import db.model.bilibili.MenuModel; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @@ -10,9 +10,10 @@ import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/menu") -public class MenuController extends BaseController { +public class MenuController extends BiliController { - @RequestMapping + + @RequestMapping() public String find(Model model, MenuModel queryCommand, @RequestParam Integer firstResult, @RequestParam Integer maxResults){ model.addAttribute("menus", super.find(DBAction.R, queryCommand, firstResult, maxResults).toString()); return "menu"; diff --git a/web/src/main/java/web/controller/TableController.java b/web/src/main/java/web/controller/TableController.java new file mode 100644 index 0000000..cbdff00 --- /dev/null +++ b/web/src/main/java/web/controller/TableController.java @@ -0,0 +1,47 @@ +package web.controller; + +import core.service.BaseService; +import db.AbstractModel; +import db.DBAction; +import db.PageResult; +import db.Type; +import org.springframework.dao.DataAccessException; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; + +public abstract class TableController extends BaseController { + @RequestMapping("table") + public String find(Model model, T queryCommand, @RequestParam Integer firstResult, @RequestParam Integer maxResults){ + DBAction action=DBAction.R; + log.info(queryCommand.tableNote()+ "进行批量" + action.getCh() + "操作请求"); + PageResult result; + if(checkAction(action)) { + try { + Long rowCount=service.rowCount(queryCommand.getClass()); + if(rowCount>0) { + List list = service.find(queryCommand, firstResult*maxResults, maxResults); + result=new PageResult(rowCount, firstResult,list,maxResults , Type.success); + }else{ + result=new PageResult(Type.fail,"没有记录"); + } + } catch (DataAccessException e) { + log.error(e); + result=new PageResult(Type.fail,"非法操作"); + } + }else{ + result=new PageResult(Type.fail,queryCommand.tableNote() + "不允许" + action.getCh() + "操作"); + } + + model.addAttribute("datas", result); + return "table"; + } + + + @Override + protected boolean checkAction(DBAction action) { + return false; + } +} diff --git a/web/src/main/java/web/html/ElementId.java b/web/src/main/java/web/html/ElementId.java new file mode 100644 index 0000000..967fbdc --- /dev/null +++ b/web/src/main/java/web/html/ElementId.java @@ -0,0 +1,29 @@ +package web.html; + +import java.util.HashMap; +import java.util.Map; + +public enum ElementId { + menu("menu_"), + button("btn_"), + iframe("iframe_") + ; + + private String id; + + ElementId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public static Map getAll(){ + Map map=new HashMap<>(); + for(ElementId id:ElementId.values()){ + map.put(id.name(),id); + } + return map; + } +} diff --git a/web/src/main/java/web/service/BiliService.java b/web/src/main/java/web/service/BiliService.java new file mode 100644 index 0000000..d9e3909 --- /dev/null +++ b/web/src/main/java/web/service/BiliService.java @@ -0,0 +1,14 @@ +package web.service; + +import core.service.BaseService; +import db.config.HibernateConfig; +import org.springframework.orm.hibernate5.HibernateTemplate; +import org.springframework.stereotype.Service; + +@Service +public class BiliService extends BaseService { + @Override + protected HibernateTemplate getHibernateTemplate() { + return HibernateConfig.get("test2"); + } +} diff --git a/web/src/main/java/web/service/DataService.java b/web/src/main/java/web/service/DataService.java index 37252ff..7982c0d 100644 --- a/web/src/main/java/web/service/DataService.java +++ b/web/src/main/java/web/service/DataService.java @@ -1,12 +1,14 @@ package web.service; import core.service.BaseService; -import db.model.CidEntity; -import db.model.DataModel; +import db.config.HibernateConfig; +import db.model.bilibili.CidEntity; +import db.model.bilibili.DataModel; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.Session; import org.hibernate.query.NativeQuery; +import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Service; @@ -25,6 +27,11 @@ public class DataService extends BaseService { private boolean isStop; + @Override + protected HibernateTemplate getHibernateTemplate() { + return HibernateConfig.get("test1"); + } + public void start(Integer threadSize){ isStop=false; executor = new ThreadPoolTaskExecutor(); @@ -99,12 +106,12 @@ public class DataService extends BaseService { private void save(Integer id) { try { - DataModel dataModel = baseDao1.get(DataModel.class, id); - CidEntity cidEntity = baseDao1.get(CidEntity.class, id); + DataModel dataModel = getHibernateTemplate().get(DataModel.class, id); + CidEntity cidEntity = getHibernateTemplate().get(CidEntity.class, id); if (dataModel != null && cidEntity != null && cidEntity.getTypeid() != null) { dataModel.setTypeId(cidEntity.getTypeid()); - baseDao2.executeWithNativeSession((Session session) -> { + getHibernateTemplate().executeWithNativeSession((Session session) -> { session.beginTransaction(); int i = 1; String sql = "insert into data_" + cidEntity.getTypeid() + " (aid, author, backup_vid, cache, cover, dispatch, dispatch_servers, dp_done, dp_done_flv, dp_done_hdmp4, dp_done_mp4, duration, files, letv_addr, letv_vid, letv_vu, mid, page, storage, storage_server, subtitle, title, type, type_id, upload, upload_meta, vid, vp, cid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; @@ -123,4 +130,5 @@ public class DataService extends BaseService { } } + } diff --git a/web/src/main/java/web/util/DynamicTimer.java b/web/src/main/java/web/util/DynamicTimer.java index 06bed33..f0fa126 100644 --- a/web/src/main/java/web/util/DynamicTimer.java +++ b/web/src/main/java/web/util/DynamicTimer.java @@ -1,19 +1,18 @@ package web.util; -import core.dao.BaseDao1; -import db.model.ScheduledTaskEntity; -import db.model.TaskEntity; +import db.model.bilibili.ScheduledTaskEntity; +import db.model.bilibili.TaskEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.config.TriggerTask; import org.springframework.scheduling.support.CronTrigger; -import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.Resource; @@ -25,16 +24,17 @@ import java.util.List; * Created by reborn on 2017/5/8. * 动态定时器任务管理类 */ -@Component +//@Component public class DynamicTimer extends ScheduledTaskRegistrar { private static Logger log=LogManager.getLogger(); - @Resource - private BaseDao1 baseDao; + + @Resource + private HibernateTemplate hibernateTemplate; @PostConstruct public void init(){ - List taskList=baseDao.loadAll(ScheduledTaskEntity.class); + List taskList=hibernateTemplate.loadAll(ScheduledTaskEntity.class); for(ScheduledTaskEntity task:taskList){ addTriggerTask(task); } diff --git a/web/src/main/resources/config.properties b/web/src/main/resources/config.properties index 8e1b01b..2b9243a 100644 --- a/web/src/main/resources/config.properties +++ b/web/src/main/resources/config.properties @@ -1,16 +1,8 @@ -#-----------------------hibernate\u914D\u7F6E----------------------------- +#hibernate\u914D\u7F6E +db_url=jdbc:mysql://mysql.sukura.top:8635/rootdb?serverTimezone=UTC&useSSL=false +db_username=sukura +db_password=Luffy9412! hibernate.dialect=org.hibernate.dialect.MySQL57Dialect hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver -#\u6570\u636E\u6E901 -hibernate.connection.url=jdbc:mysql://sukura.top:3306/bilibili?serverTimezone=UTC&useSSL=false -hibernate.connection.username=sukura -hibernate.connection.password=@ -#\u6570\u636E\u6E902 -hibernate.connection.url2=jdbc:mysql://mysql.sukura.top:8635/bilibili?serverTimezone=UTC&useSSL=false -hibernate.connection.username2=sukura -hibernate.connection.password2=Luffy9412! -#-----------------------DruidDataSource\u914D\u7F6E----------------------- -druid.maxActive=20 - -spring.scan=core,web,db -sessionFactory.scan=db.model \ No newline at end of file +#DruidDataSource\u914D\u7F6E +druid.maxActive=20 \ No newline at end of file diff --git a/web/src/main/resources/db.properties b/web/src/main/resources/db.properties new file mode 100644 index 0000000..96c44ed --- /dev/null +++ b/web/src/main/resources/db.properties @@ -0,0 +1,13 @@ + + +# +# +##\u6570\u636E\u6E901 +#hibernate.connection.url1=jdbc:mysql://sukura.top:3306/bilibili?serverTimezone=UTC&useSSL=false +#hibernate.connection.username1=sukura +#hibernate.connection.password1=@ +# +##\u6570\u636E\u6E902 +#hibernate.connection.url2=jdbc:mysql://mysql.sukura.top:8635/bilibili?serverTimezone=UTC&useSSL=false +#hibernate.connection.username2=sukura +#hibernate.connection.password2=Luffy9412! \ No newline at end of file diff --git a/web/src/main/webapp/WEB-INF/jsp/index.jsp b/web/src/main/webapp/WEB-INF/jsp/index.jsp index 7dc795b..c2fc9db 100644 --- a/web/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/web/src/main/webapp/WEB-INF/jsp/index.jsp @@ -32,7 +32,7 @@ $(this).addClass('active'); $(this).siblings().removeClass('active'); - iframe=$('#iframe_'+$(this).data("id")); + iframe=$('#${elementPreifx['iframe'].id}'+$(this).data('id')); iframe.addClass('active show'); iframe.siblings().removeClass('active show'); @@ -50,7 +50,7 @@ button.remove(); - $('#iframe_'+button.data("id")).remove(); + $('#${elementPreifx['iframe'].id}'+$(this).parent().data('id')).remove(); }); }); diff --git a/web/src/main/webapp/WEB-INF/jsp/menu.jsp b/web/src/main/webapp/WEB-INF/jsp/menu.jsp index 75a8783..a176912 100644 --- a/web/src/main/webapp/WEB-INF/jsp/menu.jsp +++ b/web/src/main/webapp/WEB-INF/jsp/menu.jsp @@ -7,10 +7,11 @@ --%> -<%@ page pageEncoding="utf-8"%> +<%@ page pageEncoding="utf-8" %> + + -table + + + + + + + + + + + + + + + + + + + + + + + + + + +
cidaidtitlesubtitleauthor
${data.cid}${data.aid}${data.title}${data.subtitle}${data.author}
+ + + + +
+
+

+ Showing ${(datas.currentPage-1)*datas.pageSize+1} to ${datas.currentPage*datas.pageSize} + of ${datas.count} entries +

+
+
+ +
+
+
+
+ + + +
diff --git a/web/src/test/java/SpringTest.java b/web/src/test/java/SpringTest.java index efb49f7..e2c25e9 100644 --- a/web/src/test/java/SpringTest.java +++ b/web/src/test/java/SpringTest.java @@ -1,6 +1,5 @@ -import core.dao.BaseDao1; -import db.model.CidEntity; -import db.model.DataModel; +import db.model.bilibili.CidEntity; +import db.model.bilibili.DataModel; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; @@ -14,25 +13,25 @@ import org.hibernate.criterion.Projections; import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import web.config.AppConfig; import web.config.SpringConfig; +import web.service.DataService; import javax.annotation.Resource; import java.io.File; @@ -48,14 +47,21 @@ import java.util.List; public class SpringTest { private static Logger log = LogManager.getLogger(); + private MockMvc mockMvc; + + @Autowired + WebApplicationContext wac; + @Resource - private BaseDao1 baseDao1; + private DefaultListableBeanFactory beanFactory; + @Resource + private DataService dataService; - private MockMvc mockMvc; @Autowired - WebApplicationContext wac; + @Qualifier("hibernateTemplate_test1") + private HibernateTemplate baseDao1; @Before public void setup(){ @@ -63,15 +69,15 @@ public class SpringTest { } - @Test public void test() throws Exception { - ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/menu").param("firstResult","0").param("maxResults","0")); + ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/data/table").param("firstResult","0").param("maxResults","10")); resultActions.andDo(MockMvcResultHandlers.print()).andReturn(); } // @Test public void exportTableSql() { + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(baseDao1.getSessionFactory().getProperties()).build(); Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(DataModel.class).buildMetadata(); SchemaExport schemaExport = new SchemaExport(); @@ -131,16 +137,11 @@ public class SpringTest { } } -// @Test + @Test public void test4() throws IOException { - DetachedCriteria criteria = DetachedCriteria.forClass(DataModel.class); - List dataEntities = (List) baseDao1.findByCriteria(criteria, 10, 10); - for (DataModel dataEntity : dataEntities) { - log.info(dataEntity.getCid()); - } // 查询总条数 - Long count = baseDao1.executeWithNativeSession((Session session) -> (Long) DetachedCriteria.forClass(DataModel.class).setProjection(Projections.rowCount()).setProjection(Projections.groupProperty("groupId")).getExecutableCriteria(session).uniqueResult()); - + Long count = baseDao1.executeWithNativeSession((Session session) -> (Long) DetachedCriteria.forClass(DataModel.class).setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult()); + log.info(count); } } diff --git a/web/src/test/java/Test.java b/web/src/test/java/Test.java index d9caf23..5b4ed14 100644 --- a/web/src/test/java/Test.java +++ b/web/src/test/java/Test.java @@ -1,3 +1,5 @@ +import db.annotation.BiliBili; +import db.util.ClassScaner; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -5,6 +7,6 @@ public class Test { private static Logger log = LogManager.getLogger(); public static void main(String[] args) { - + ClassScaner.scan("db.model",BiliBili.class).forEach(aClass -> System.out.println(aClass)); } } diff --git a/web/src/test/java/web/controller/TestController.java b/web/src/test/java/web/controller/TestController.java index 706c419..555ec73 100644 --- a/web/src/test/java/web/controller/TestController.java +++ b/web/src/test/java/web/controller/TestController.java @@ -2,14 +2,13 @@ package web.controller; import db.DBAction; import db.model.TaskModel; -import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/test") -public class TestController extends BaseController{ +public class TestController extends BiliController{ + @Override public boolean checkAction(DBAction action) {