spring-boot 代码示例1
标识符无效 实体表跟数据库字段不一样 &代表在后台运行 nohup 意思是不挂断运行命令,当账户退出或终端关闭时,程序仍然运行 nohup java -jar sam-service-mongo-0.0.1.jar -server -Xms256m -Xmx1024m -Xss256k > ./run.log 2>&1 & nohup java -jar sam-service-mongo-0.0.1.jar > ./run.log 2>&1 & Hibernate实体类注解中忽略某些字段的映射需要给字段加 @Transient 注解 如: @Transient private Double income; @Transient private Double profit; 如果 findByName_szhNotId 某个字段是下划线 用字段属性查询时会报错 必须使用 @Query ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- @RestController @RequestMapping("/com") public class ComService extends BaseService { private static Logger logger = Logger.getLogger(ComService.class); @Autowired private DictIndustryDao DdctIndustryDao; @RequestMapping(value = "/search") public String stockSearch(String name) { return null; } @RequestMapping(value = "/stock/show", method = RequestMethod.POST) public String stockShow(@RequestParam("id") String id) { return null; } @RequestMapping(value = "/stock/add", method = RequestMethod.POST) public String stockAdd(ComBaseInfoParam param) { return null; } } ---------------------------------------------------------------------------------------------------------------- @Repository public class DictIndustryDao { @Autowired private DictIndustryRepository dictIndustryRepository; public Long saveByPk(DictIndustry industry) { // 根据有没有主键是否新增更新 自带方法 新增 更新都可以此方法 industry = dictIndustryRepository.save(industry); return industry.getId(); } //根据实体对象里面有值的去删除 自带方法 public void remove(DictIndustry industry) { dictIndustryRepository.delete(industry); logger.info(industry.getId() + "数据删除"); } // 根据主键删除 自带方法 public void delete(Long id) { dictIndustryRepository.delete(id); logger.info(industry.getId() + "数据删除"); } } public interface DictIndustryRepository extends JpaRepository<DictIndustry, Long> { DictIndustry findByCode(String code); DictIndustry findByZhsnameAndLeve(String zhsname, Integer leve); } ------------------------------------------------------------------------ @Repository public class SamRepository { private BaseStockDao baseStockDao; private DictProductRsDao dictProductRsDao; @Autowired private FinSamDao finSamDao; // 使用spring 的 jdbcTemplate 进行查询 @Autowired private JdbcTemplate jdbcTemplate; @Autowired public SamRepository(BaseStockDao baseStockDao,DictProductRsDao dictProductRsDao) { this.baseStockDao = baseStockDao; this.dictProductRsDao = dictProductRsDao; } // 使用jdbcTemplate 查询 自动将sql转化为对应的实体类 public List<FinSamProduct>(){ String sql = "select * from fin_sam_product f where 1=1 and f.active = 1 "; // import org.springframework.jdbc.core.BeanPropertyRowMapper; // FinSamProduct 是对应的实体类 此查询关联的表不会查询出来 List<FinSamProduct> dataList = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(FinSamProduct.class)); return dataList; } // 使用jdbcTemplate 删除 public String stockDel(String pcode, String secu, String[] fp, String year) throws Exception { if (fp == null || fp.length == 0) { return "year is null"; } String sql = "DELETE from FIN_SAM_PRODUCT_ITEM t WHERE t.ref in (SELECT id from FIN_SAM_PRODUCT m WHERE " + "m.SECU = '#secu' and m.FP in (#year)) and t.CD in (SELECT s.CODE from DICT_PRODUCT_RS s WHERE s.code = '#pcode' " + "or s.id in ( SELECT r.ref from dict_product_ref r where r.typ = 'ancestors' and r.code = '#pcode' ))"; sql = sql.replaceAll("#secu", secu).replaceAll("#year", year).replaceAll("#pcode", pcode); System.out.println("sql -> " + sql); jdbcTemplate.execute(sql); return "success"; } } ------------------------------------------------------------------------ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.stereotype.Repository; @Repository public class SupplyChainRelationDao { @Autowired private SupplyChainRelationRepository supplyChainRelationRepository; @Autowired private DictProductRsRepository dictProductRsRepository; // 根据实体对象里面有值的去查询 自带方法 public List<SupplyChainRelation> findQuery(SupplyChainRelation chainRelation) { Example<SupplyChainRelation> example = Example.of(chainRelation); return supplyChainRelationRepository.findAll(example); } // 根据主键查询 自带方法 public DictProductRs findOneById(String id) { return dictProductRsRepository.findOne(Long.valueOf(id)); } private List<DictProductRs> findSun(String code) { List<ProductRsOrAncestors> data = dictProductRefRepository.findByancestors(code); ArrayList<Long> ids = new ArrayList<>(); if (CollectionUtils.isNotEmpty(data)) { data.forEach(v -> ids.add(v.getRef())); } return dictProductRsRepository.findAll(ids); // 根据多个主键查询 自带方法 Iterable<ID> ids } } ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- public interface DictProductRsRepository extends JpaRepository<DictProductRs, Long> { @Query("from DictProductRs r where r.valid = '1' ") List<DictProductRs> findValidate(); DictProductRs findByCode(String code); @Query("from BaseStock s where s.name_szh = ?1") BaseStock findByName_szh(String name_szh); // 如果属性里面是 name_szh 带有下划线的 属性 不能使用此方法 必须使用 @Query // List<DictProductRs> findByName_szh(String name_szh); @Query("from DictProductRs r where r.valid = '1' and ( r.code in ?1 or r.name_szh like ?2 or r.name_en like ?2 )") List<DictProductRs> search(Collection<String> codes, String name); List<DictProductRs> findByCodeIn(Collection<String> totalCodeSet); } ------------------------------------------------------------------------ public interface DictProductDefRepository extends JpaRepository<DictProductDef, Long> { DictProductDef findBySecuAndName(String secu, String name); DictProductDef findByItemcdAndSecuAndCode(String itemcd,String secu,String code); List<DictProductDef> findByNameLike(String name); } ------------------------------------------------------------------------ public interface BaseStockRepository extends JpaRepository<BaseStock,Long> { BaseStock findByTick(String tick); BaseStock findByCode(String code); @Query("from BaseStock b where b.name_szh = ?1") BaseStock findByName_szh(String name_szh); @Query("from BaseStock b where b.id <> ?1 and b.name_szh = ?2") BaseStock findByName_szhNotId(Long id, String name_szh); } ------------------------------------------------------------------------ import com.csf.sam.entity.SupplyChainRelation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface SupplyChainRelationRepository extends JpaRepository<SupplyChainRelation,Long> { @Query("from SupplyChainRelation s where s.rdegree = 1 and s.rtyp = ?1") List<SupplyChainRelation> findByRtyp(String rtyp); @Query("from SupplyChainRelation s where s.rdegree = 1") List<SupplyChainRelation> findByRdegree(); @Query("from SupplyChainRelation s where s.rdegree = 1 and s.prime_szh = ?1") List<SupplyChainRelation> findBySzh(String szh); @Query("from SupplyChainRelation s where s.rdegree = 1 and s.prime_cd = ?1") List<SupplyChainRelation> findByCode(String code); @Query("from SupplyChainRelation s where s.prime_cd in ?1 and s.level = ?2 and s.rdegree = ?3") List<SupplyChainRelation> findByPrime_cdInAndLevelAAndRdegree(Collection<String> codes, Integer level, Integer rdegree); // 使用原生的sql执行 @Query(value = " select count(1) from supply_chain_relation s where s.prime_cd = ?1 and s.leve = ?2 and s.related_cd =?3 ", nativeQuery = true) Long countByPrime_cdAndLevelAndRelated_cd(String prime_cd, Integer level, String related_cd); @Query(" from SupplyChainRelation s where s.prime_cd = ?1 and s.level = ?2 and s.rtyp = ?3 and s.related_cd = ?4 ") SupplyChainRelation findByPrime_cdAndLevelAndRtypAndRelated_cd(String prime_cd, Integer level, String rtyp, String related_cd); @Transactional @Modifying @Query(" delete from SupplyChainRelation s where s.prime_cd = ?1 and s.level = ?2 and s.rtyp = ?3 and s.related_cd = ?4") void deleteByPrime_cdAndLevelAndRtypAndRelated_cd(String prime_cd, Integer level, String rtyp, String related_cd); @Query(" from SupplyChainRelation s where s.prime_cd = ?1") List<SupplyChainRelation> findByPrime_cd(String prime_cd); } ------------------------------------------------------------------------ public interface FinSamRepository extends JpaRepository<FinSamProduct, Long> { List<FinSamProduct> findByIdInAndQIn(List<Long> ids, Collection<String> q); List<FinSamProduct> findBySecuAndQIn(String secu, Collection<String> q); List<FinSamProduct> findBySecuLike(String secu); List<FinSamProduct> findByIdIn(List<Long> ids); List<FinSamProduct> findBySecuAndFpIn(String secu, List<String> fp); // 测试过 // 根据id降序排序取第一条数据 first跟top相对应 FinSamProduct findFirstByOrderByIdDesc(); } ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @Entity来注解实体类时指定name为此实体类对应的表名 * 此对应oracle数据库 */ @Table(name = "fin_product_node_ref") @Entity public class FinNode implements Serializable { // JPA默认的递增大小是50 所以这里要设置allocationSize=1,就是以1递增 // 这里需要手动创建 sequence ---> create sequence seq_base_stock start with 65422 increment by 1; // seq_base_stock idSequenceseq 名字可以随便起 @Id @SequenceGenerator(name = "idSequenceseq", sequenceName = "seq_base_stock", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idSequenceseq") private Long id; private String oid; private Long ref; //FinProductNode id private String code; //节点code private String income; //收入 // oracle类型为 deal number(20), private Boolean dual; //收入 当这里取值为1时自动转化为true,为0时自动转化为false private String income_ratio; //收入占比 @Column (name = "leve") // 声明数据库指定的字段名称 private Integer level;//层级 // 忽略此字段对数据库的映射 @Transient private Double income; // 关联另外一张表fin_sam_product_item 关联字段为fin_sam_product_item.ref字段 // 只用来关联查询 关联更新 关联删除不行 @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER,mappedBy = "ref") private List<ProductItem> items; //#@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "ref") //# 实体类如果关联查询使用懒惰加载 fetch = FetchType.LAZY 必须加上以下代码 不然会报 no session 异常 //spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true } @Entity @Table(name = "fin_sam_product_item") public class ProductItem { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_FIN_SAM_PRODUCT") @SequenceGenerator(name = "SEQ_FIN_SAM_PRODUCT", sequenceName = "SEQ_FIN_SAM_PRODUCT_ITEM", allocationSize = 1) private Long id; private Long ref; @Transient private Double income; @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER,mappedBy = "ref") private List<ProductItemOVo> oVos; @Transient private List<ProductItemOVo> o; @Transient private List<ProductItemOVo> ro; } ---------------------------------------------------------------------------------------------------------------- public class ComBaseInfoParam implements Serializable{ private String id; private String tick;// 股票代码 private String nameszh; // 公司全称 private String abbrszh; // 公司简称 private String mktcode; // 市场 1001 1002 1003 1012 1052 private String lscode; // 上市/退市 private String lsdt; // 上市时间/退市时间 private String edt; // 退市时间 ......... } ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- oracle 连接信息 application.properties 文件 # 指定项目的端口号 server.port=8182 # 指定项目访问时的路径的前缀 server.context-path=/api debug=true # 使运行时输入sql语句 spring.jpa.show-sql=true # @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "ref") # 实体类如果关联查询使用懒惰加载 fetch = FetchType.LAZY 必须加上以下代码 # spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true spring.jpa.database=oracle spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@192.168.100.10:1521:csdb001 spring.datasource.password=zhaoshang spring.datasource.username=zhaoshang 备注 : 项目访问 http://192.168.100.15:8182/api/com/search