spring data jpa 多表联合查询 , 查询结果 List 为空无法映射 5C

一方
package com.jpa.vo;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "role")
public class RoleVO implements Serializable {

@Id
@GeneratedValue(strategy  = GenerationType.AUTO)
@Column(name = "role_id")
private Integer roleId;

@Column(name = "role_name")
private String  roleName;

@ManyToOne
@JoinColumn(name="role_id",insertable =  false , updatable = false)
private UserVO userVO;

}

多方
package com.jpa.vo;

import javax.annotation.sql.DataSourceDefinition;
import javax.persistence.*;
import java.util.List;

/**

  • 用户信息类
    */
    @Entity
    @Table(name="users")
    public class UserVO {

    @Column(name="role_id")
    private Integer roleId;

    @Id
    @Column(name = "user_id")
    @GeneratedValue
    private Integer userId;

    @Column( name="user_name")
    private String userName;

    @Column(name ="pass_word")
    private String password;

    @OneToMany( cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userVO")
    List roles;

}

spring data jpa 多表联合查询 , 查询结果 List 为空无法映射

{
"roleId": 1,
"userId": 1,
"userName": "wuming",
"password": "1234",
"roles": [
{}
]
}

2个回答

这个问题已经自己解决了

qq_28381495
qq_28381495 楼主怎么解决的,我也遇到一样的问题
5 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring boot + Spring Data JPA + Hibernate缓存问题
如题,项目框架为Spring boot + Spring Data JPA + Hibernate,hibernate中有Query.list()和query.iterator()方法,其中query.iterator()方法去查询时会用到缓存,返回的参数类型是Iterator,如果使用Spring Data JPA+hibernate如何实现查询一个list使用到缓存呢,JPA中的PagingAndSortingRepository接口中的findAll()方法返回的Iterator类型好像和query.iterator()的效果不一样,哪个哥们可以解答下,万分感激!
spring data jpa 一对多关系怎么配置
``` //实体类1 @Entity @Table(name = "t_user") //@Data //@ToString(exclude = {"role"}) public class TUser { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Integer id; private String username; private String password; private String email; private Integer sex;//性别,0.1.2(男,女,未知) private Date last_login; private Date create_time;//创建时间 private Date update_time;//修改时间 private String phone;//电话 private String photo;//图片地址 private Integer status;//状态,0正常,1禁止 @ManyToOne(cascade=CascadeType.PERSIST)//cascade=CascadeType.PERSIST(开启级联操作) @JoinColumn(name="roles_id") private TRole role; } //实体类2 @Entity @Table(name = "t_role") //@Data public class TRole { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Integer id; private String memo; private String r_name; private Date ctime; private Date update_time; @OneToMany(mappedBy="role") private Set<TUser> set = new HashSet<>(); } //dao层 public interface TUserDao extends JpaRepository<TUser, Integer>{ } //测试代码 @Autowired private TUserDao tuserDao; //添加 @Test public void add() { TRole role = new TRole(); role.setCtime(new Date()); role.setMemo("注解"); role.setR_name("管理员"); role.setUpdate_time(new Date()); TUser tUser = new TUser(); tUser.setCreate_time(new Date()); tUser.setEmail("1655@qa.com"); tUser.setLast_login(new Date()); tUser.setPassword("123456"); tUser.setPhone("www"); tUser.setPhoto("www.as"); tUser.setSex(0); tUser.setStatus(0); tUser.setUpdate_time(new Date()); tUser.setUsername("nichen"); role.getSet().add(tUser); tUser.setRole(role); tuserDao.save(tUser); } //查询 @Test public void findAll() { List<TUser> findAll = tuserDao.findAll(); for (TUser tUser : findAll) { System.out.println("tUser:"+tUser); } System.out.println("size:"+findAll.size()); } 这代码插入是可以的,查询就会有问题。 测试中的查询的错误:org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.simulation.admin.model.TRole.set, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:299) at java.lang.String.valueOf(String.java:2994) at java.lang.StringBuilder.append(StringBuilder.java:131) at com.simulation.admin.model.TRole.toString(TRole.java:99) at java.lang.String.valueOf(String.java:2994) at java.lang.StringBuilder.append(StringBuilder.java:131) at com.simulation.admin.model.TUser.toString(TUser.java:166) at java.lang.String.valueOf(String.java:2994) at java.lang.StringBuilder.append(StringBuilder.java:131) at com.simulation.admin.SimulationApplicationTests.findAll(SimulationApplicationTests.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73) at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) 如果是用服务的接口访问的错误:java.lang.StackOverflowError: null at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:136) ~[na:1.8.0_144] at java.sql.Timestamp.toString(Timestamp.java:302) ~[na:1.8.0_144] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:165) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at java.util.AbstractCollection.toString(AbstractCollection.java:462) ~[na:1.8.0_144] at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:300) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TRole.toString(TRole.java:99) ~[classes/:na] at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_144] at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_144] at com.simulation.admin.model.TUser.toString(TUser.java:166) ~[classes/:na] ```
Spring Data jpa+Mongodb查询全部数据出错
代码: List<Comment> comments = commentDao.findAll(); findAll为继承自MongoRepository的方法 报错: Caused by: com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'Field 'locale' is invalid in: { locale: "comment" }' on server localhost:27017 at com.mongodb.operation.FindOperation$1.call(FindOperation.java:735) at com.mongodb.operation.FindOperation$1.call(FindOperation.java:725) at com.mongodb.operation.OperationHelper.withReadConnectionSource(OperationHelper.java:463) at com.mongodb.operation.FindOperation.execute(FindOperation.java:725) at com.mongodb.operation.FindOperation.execute(FindOperation.java:89) at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:189) at com.mongodb.client.internal.MongoIterableImpl.execute(MongoIterableImpl.java:143) at com.mongodb.client.internal.MongoIterableImpl.iterator(MongoIterableImpl.java:92) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2793) ... 86 more 试过换工程、换数据库、换表、换版本,依旧没有解决,而且几乎搜不到这个错误。
spring data JPA 类型转换异常
工作中使用spring data jpa 遇到一个百思不得姐的问题,劳烦各位大佬帮忙指点迷津。,小老弟感激不尽!! DAO : package com.xhsceis.credit.repository.firstScreenRepository; import com.xhsceis.credit.entity.FsManageStatus; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface FsManageStatusRepository extends JpaRepository<FsManageStatus,String> { @Query(value = "SELECT FS.changPing,FS.chaoYang FROM FsManageStatus FS") List<FsManageStatus> getFsManageStatus(); } SERVICE: List<FsManageStatus> fsManageStatusList = fsManageStatusRepository.getFsManageStatus(); for **(FsManageStatus fsManageStatus : fsManageStatusList)** { Map<String, Object> fsManage = Maps.newHashMap(); Map<String, Object> data = Maps.newHashMap(); data.put("changPing", fsManageStatus.getChangPing()); data.put("chaoYang", fsManageStatus.getChaoYang()); } ENTITY: @Entity @Table(name = "FS_MANAGE_STATUS") public class FsManageStatus { @Id @Column(name = "STATUS") private String status; @Column(name = "DONG_CHENG") private String dongCheng; @Column(name = "FENG_TAI") private String fengTai; @Column(name = "DA_XING") private String daXing; @Column(name = "MI_YUN") private String miYun; @Column(name = "PING_GU") private String pingGu; @Column(name = "YAN_QING") private String yanQing; @Column(name = "HUAI_ROU") private String huaiRou; @Column(name = "FANG_SHAN") private String fangShan; @Column(name = "CHANG_PING") private String changPing; @Column(name = "CHAO_YANG") private String chaoYang; @Column(name = "HAI_DIAN") private String haiDian; @Column(name = "SHI_JING_SHAN") private String shiJingShan; @Column(name = "XI_CHENG") private String xiCheng; @Column(name = "TONG_ZHOU") private String tongZhou; @Column(name = "MEN_TOU_GOU") private String menTouGou; @Column(name = "SHUN_YI") private String shunYi; @Column(name = "COUNT") private String count; 问题描述:service 查出来的数据对象集合,我遍历的时候,报错说类型转换异常 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.xhsceis.credit.entity.FsManageStatus 我猜应该是jpa查到的数据没有给指定成集合对象来接收,而是自己默认为object存储的。这是我的猜想,最后,还是得麻烦大佬给解答一哈儿。
Spring Data JPA的@Query注解 的sq语句问题
使用spring jpa 的时候需要自己写个查询但是不会, 请教下: ``` @Entity class B{ @Id @GeneratedValue private Integer id; private String atrrB; @OneToMany(mappedBy = "b" ) private List<A> as; ... /* id,atrrB,as的Setter&Getter */ } @Entity class A{ @Id @GeneratedValue private Integer id; @ManyToOne @JoinColumn(a_id) private B b ; private String atrrA; ... /* id,atrrA,b的Setter&Getter */ } interface ARepository extends JpaRepository <A,Integer>{ @Query("不会啊") public List<A> getReslut(String atrrA_key, String atrrB_key); } ``` 那个sql语句不会,希望结果可以得到所有A表格里所有atrrA属性like查询方法第一个参数And A表格里的b.atrrB属性 like 查询方法的第二个参数的所有条目。
Spring data Jpa批量更新操作
注释掉的方法,速度太慢6000条要四五分钟,没注释掉的方法出现空指针异常,不知道怎么解决。。。。。求大神 异常: ``` Exception in thread "main" java.lang.NullPointerException at service.UserServiceImpl.updateUser(UserServiceImpl.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at $Proxy23.updateUser(Unknown Source) at test.Login.update(Login.java:49) at test.Login.main(Login.java:26) ``` login.java ``` public static void update(UserService userService) throws UserNotFound { // // for(int i=497;i<6497;i++) // { // User u=new User(); // u.setId(i); // u.setName("ds"); // userService.updateUser(u); // } List<User> user=new ArrayList<User>(); for(int i=497;i<6497;i++) { User u=new User(); u.setId(i); u.setName("d"); user.add(u); } userService.updateUser(user); } ``` UserServiceImpl ``` @Autowired private UserRepository userRepository; private EntityManager em; //修改用户 @Transactional public void updateUser(List<User> user) throws UserNotFound { // 根据Id查找user // User userUpdate=userRepository.findOne(user.getId()); // if(userUpdate==null) // throw new UserNotFound(); // // if(userUpdate.getName()!=null) // userUpdate.setName(user.getName()); // // userRepository.save(userUpdate); // // for(int i=0;i<user.size();i++) { em.merge(user.get(i)); if(i%30==0) { em.flush(); em.clear(); } } } ```
spring data jpa 怎么查询一个字段的总和?
不用sql实现,用类似这种方法实现 Long num = taskUserTaskHistoryEditDao.count(new Specification<TaskUserTaskHistoryEdit>() { @Override public Predicate toPredicate(Root<TaskUserTaskHistoryEdit> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> predicateList = new ArrayList<>(); predicateList.add(criteriaBuilder.equal(root.get("taskId"),taskId)); criteriaQuery.where(criteriaBuilder.and(predicateList.toArray(new Predicate[]{}))); return criteriaQuery.getRestriction(); } });
spring data jpa的误将方法名当成属性名称的问题
项目中使用了spring data jpa,自己扩展了一个全局接口AbstractJxetRepository [code="java"]public interface AbstractJxetRepository<T> { public void batchInster(List<T> list, int size) throws Exception; public void batchUpdate(List<T> list, int size) throws Exception; }[/code] 实现类AbstractDao [code="java"]@NoRepositoryBean public abstract class AbstractDao<T> implements AbstractJxetRepository<T> { @PersistenceContext protected EntityManager em; @Transactional public void batchInster(List<T> list, int size) throws Exception{ for (int i = 0; i < list.size(); i++) { em.persist(list.get(i)); if (i % size == 0) { em.flush(); em.clear(); } } } @Transactional public void batchUpdate(List<T> list, int size) { for (int i = 0; i < list.size(); i++) { em.merge(list.get(i)); if (i % size == 0) { em.flush(); em.clear(); } } } }[/code] 在一个模块接口中继承AbstractJxetRepository [code="java"]public interface EduUnitLevelDao extends PagingAndSortingRepository<EduUnitLevel, Integer>, JpaSpecificationExecutor<EduUnitLevel> { public List<EduUnitLevel> getBySchoolId(Integer schoolId); @SuppressWarnings("unchecked") public EduUnitLevel save(EduUnitLevel eduUnitLevel); public List<EduUnitLevel> save(List<EduUnitLevel> eduUnitLevels);[/code] 现在的问题是,在service中调用EduUnitLevelDao ,会将batchInster方法中的batch当做EduUnitLevel的属性,提示No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel 全部的报错信息 [code="java"]org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cn.com.jxet.datalayer.service.EduUnitLevelServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.com.jxet.datalayer.service.EduUnitLevelService cn.com.jxet.datalayer.service.EduUnitLevelServiceTest.eduUnitLevelService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void cn.com.jxet.datalayer.service.EduUnitLevelService.setEduUnitLevelDao(cn.com.jxet.datalayer.dao.EduUnitLevelDao); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelDao': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:379) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cn.com.jxet.datalayer.service.EduUnitLevelService cn.com.jxet.datalayer.service.EduUnitLevelServiceTest.eduUnitLevelService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void cn.com.jxet.datalayer.service.EduUnitLevelService.setEduUnitLevelDao(cn.com.jxet.datalayer.dao.EduUnitLevelDao); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelDao': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) ... 26 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void cn.com.jxet.datalayer.service.EduUnitLevelService.setEduUnitLevelDao(cn.com.jxet.datalayer.dao.EduUnitLevelDao); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelDao': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1122) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) ... 28 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void cn.com.jxet.datalayer.service.EduUnitLevelService.setEduUnitLevelDao(cn.com.jxet.datalayer.dao.EduUnitLevelDao); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelDao': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:601) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) ... 39 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eduUnitLevelDao': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102) at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1448) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:249) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:558) ... 41 more Caused by: org.springframework.data.mapping.PropertyReferenceException: No property batch found for type cn.com.jxet.datalayer.entity.EduUnitLevel at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75) at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:353) at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:271) at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:245) at org.springframework.data.repository.query.parser.Part.<init>(Part.java:72) at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:180) at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:260) at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:240) at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:68) at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:57) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:90) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:162) at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:68) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:279) at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:147) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:153) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:43) at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142) ... 49 more[/code]
Spring Data Jpa 加了 @Transactional事物注解后数据异常
代码如下: ``` @Transactional public void addAdminRole(String roleIdsStr, Long userId) { if (StringUtils.isBlank(roleIdsStr)) { throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR); } // 重点是这里,在此处我只是查询了一个CommonAdmin这个实体,然后再没对这个实体做过任何curd操作,但执行完addAdminRole这个方法后,CommonAdmin数据却发生了变化 CommonAdmin ca = commonAdminService.getOne(userId); if (ca == null || ca.getStatus() != CommonStatusEnum.ENABLE.getCode()) { throw new BusinessException(ResultCodeEnum.USER_DISABLE); } // 先删除原来的角色 this.removeAdminAllRole(userId); String[] roleIds = roleIdsStr.split(","); List<AdminRole> list = new ArrayList<>(roleIds.length); AdminRole a; for (String s : roleIds) { a = new AdminRole(); a.setId(IDGen.getId()); a.setAdminUserId(userId); a.setRoleId(Long.valueOf(s)); a.setCreateTime(System.currentTimeMillis()); a.setStatus(CommonStatusEnum.ENABLE.getCode()); a.setUpdateTime(System.currentTimeMillis()); list.add(a); } this.adminRoleDao.saveAll(list); } ``` 其中getOne方法如下: ``` public CommonAdmin getOne(Long id) { CommonAdmin u = commonAdminDao.findById(id).get(); u.setCertification(""); return u; } ```
spring-data-jpa delete
现在使用spring-data-jpa为什么运行下面的代码courseDetai没有被删除呢? [code="java"]@Transactional(readOnly = false) public void deleteCourseDetail(Long id, Long courseId) { Course course = courseDao.findOne(courseId); CourseDetail courseDetail = courseDetailDao.findOne(id); System.out.println(course.getCourseDetails().size()); course.getCourseDetails().remove(courseDetail); System.out.println("after: " + course.getCourseDetails().size()); courseDao.save(course); } @OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) public List<CourseDetail> getCourseDetails() { return courseDetails; }[/code]
Spring Boot 使用JPA连接MySQL数据库报错 is not mapped
小白向各位大侠求助: 创建Spring Boot 工程时,使用JPA连接MySQL数据库,查询时报错,报错信息如下: ``` 2018-06-04 06:34:44.959 ERROR 6116 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.ast.QuerySyntaxException: Person is not mapped [select t from Person t]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Person is not mapped [select t from Person t]] with root cause org.hibernate.hql.internal.ast.QuerySyntaxException: Person is not mapped at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3706) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131] at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.0.6.RELEASE.jar:5.0.6.RELEASE] at com.sun.proxy.$Proxy76.createQuery(Unknown Source) ~[na:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131] at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:304) ~[spring-orm-5.0.6.RELEASE.jar:5.0.6.RELEASE] at com.sun.proxy.$Proxy76.createQuery(Unknown Source) ~[na:na] at com.neuqsoft.demo.repository.impl.PersonDaoImpl.findAll(PersonDaoImpl.java:52) ~[classes/:na] at com.neuqsoft.demo.repository.impl.PersonDaoImpl$$FastClassBySpringCGLIB$$7895840c.invoke(<generated>) ~[classes/:na] at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE] at com.neuqsoft.demo.repository.impl.PersonDaoImpl$$EnhancerBySpringCGLIB$$182f86eb.findAll(<generated>) ~[classes/:na] at com.neuqsoft.demo.service.PersonService.findAll(PersonService.java:50) ~[classes/:na] at com.neuqsoft.demo.controller.PersonController.getPseronList(PersonController.java:59) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.6.RELEASE.jar:5.0.6.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131] ``` 实体文件: ``` @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private String id; @Column(name="name") private String name; @Column(name="sex") private String sex; @Column(name="tel") private String tel; @Column(name="address") private String address; @Column(name="age") private String age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } } ``` 数据库表: ![图片说明](https://img-ask.csdn.net/upload/201806/04/1528064584_339931.jpg) DAO文件: ``` package com.neuqsoft.demo.repository.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.neuqsoft.demo.entity.Person; import com.neuqsoft.demo.repository.PersonDao; @Repository public class PersonDaoImpl implements PersonDao { @Autowired @PersistenceContext private EntityManager entityManager; @Override public List<Person> findAll() { return this.entityManager.createQuery("select t from Person t").getResultList(); } } ``` Pom.xml ``` <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.neuqsoft</groupId> <artifactId>DemoJPAForSpringBoot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>DemoJPAForSpringBoot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <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>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- custom renw --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` application.properties: ``` #mysql #datasource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/forspringboot?useSSL=false spring.datasource.username=root spring.datasource.password=1qaz!QAZ spring.jpa.show-sql= true ```
jpa使用@Query查询报错SQL Error: 1064, SQLState: 42000
我的sql ![图片说明](https://img-ask.csdn.net/upload/201812/25/1545728806_126381.png) sql里没有和mysql的关键字重复,但是报错SQL Error: 1064, SQLState: 42000 ``` Hibernate: select com.wangyou.waimai.model.goods.Goods g.goodsId, g.goodsName, g.goodsIcon, gs.goodsPrice from GoodsBean g, GoodsStandardPriceBean gs, TypeStandardBean ts where g.goodsId = gs.goodsId and ts.id = gs.standardId and g.shopId = 50 and g.goodsType = 48 and g.goodsState = 1 and g.regionId = 1 and gs.standardId = 35 2018-12-25 16:46:40.471 WARN 7208 --- [io-18668-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000 2018-12-25 16:46:40.474 ERROR 7208 --- [io-18668-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.model.goods.Goods g.goodsId, g.goodsName, g.goodsIcon, gs.goodsPrice from Goods' at line 1 2018-12-25 16:46:40.508 ERROR 7208 --- [io-18668-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.model.goods.Goods g.goodsId, g.goodsName, g.goodsIcon, gs.goodsPrice from Goods' at line 1 at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1024) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.2.0.jar:na] at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.2.0.jar:na] at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.getResultSet(Loader.java:2167) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1930) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.doList(Loader.java:2689) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.doList(Loader.java:2672) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.Loader.list(Loader.java:2501) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2223) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1053) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:170) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.query.Query.getResultList(Query.java:135) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:129) ~[spring-data-jpa-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135) ~[spring-data-jpa-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.3.RELEASE.jar:2.1.3.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.3.RELEASE.jar:5.1.3.RELEASE] at com.sun.proxy.$Proxy148.selectZhuGoods(Unknown Source) ~[na:na] at com.wangyou.waimai.service.goods.GoodsService.findByShopId(GoodsService.java:65) ~[classes/:na] at com.wangyou.waimai.controller.user.UsersController.enterPurchase(UsersController.java:417) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_102] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_102] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_102] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_102] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106) ~[spring-boot-actuator-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_102] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_102] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_102] ```
JPA不是自動生成表嗎?
請先看以下代碼: @Entity public class Person { ...... } @Repository public interface Person_Repository extends JpaRepository<Person, String> { } 用Person_Repository.save(Person) 后,報錯:"Table 'mirrorworld.person' doesn't exist" JPA不是自動生成表嗎? 詳細報錯如下: . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.21.RELEASE) 2019-08-27 17:18:27.082 INFO 13320 --- [ main] c.s.mirrorworld.mirrorworldApplication : Starting mirrorworldApplication on LAPTOP-FAS0SHLM with PID 13320 (C:\Users\yueho\eclipse-workspace\mirrorworld\target\classes started by yueho in C:\Users\yueho\eclipse-workspace\mirrorworld) 2019-08-27 17:18:27.091 INFO 13320 --- [ main] c.s.mirrorworld.mirrorworldApplication : No active profile set, falling back to default profiles: default 2019-08-27 17:18:27.270 INFO 13320 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@48f278eb: startup date [Tue Aug 27 17:18:27 CST 2019]; root of context hierarchy 2019-08-27 17:18:30.768 INFO 13320 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default' 2019-08-27 17:18:30.817 INFO 13320 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2019-08-27 17:18:31.040 INFO 13320 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final} 2019-08-27 17:18:31.043 INFO 13320 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2019-08-27 17:18:31.046 INFO 13320 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist 2019-08-27 17:18:31.139 INFO 13320 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 2019-08-27 17:18:31.612 INFO 13320 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2019-08-27 17:18:33.095 INFO 13320 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2019-08-27 17:18:36.919 INFO 13320 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2019-08-27 17:18:36.954 INFO 13320 --- [ main] c.s.mirrorworld.mirrorworldApplication : Started mirrorworldApplication in 10.587 seconds (JVM running for 11.489) 2019-08-27 17:18:58.429 WARN 13320 --- [WT-EventQueue-0] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1146, SQLState: 42S02 2019-08-27 17:18:58.429 ERROR 13320 --- [WT-EventQueue-0] o.h.engine.jdbc.spi.SqlExceptionHelper : Table 'mirrorworld.person' doesn't exist 2019-08-27 17:18:58.433 INFO 13320 --- [WT-EventQueue-0] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet Exception in thread "AWT-EventQueue-0" org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:525) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:209) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy74.save(Unknown Source) at com.stepforward.mirrorworld.p2_base_bean.Thing_Persistence_Service.Save_thing_simply(Thing_Persistence_Service.java:236) at com.stepforward.mirrorworld.p2_base_bean.Thing_Persistence_Service.Save_thing(Thing_Persistence_Service.java:63) at com.stepforward.mirrorworld.p2_base_bean.Thing_List_Service.Save_thing_list(Thing_List_Service.java:673) at com.stepforward.mirrorworld.p2_base_bean.Thing_List_Service.Manage_user_intention(Thing_List_Service.java:73) at com.stepforward.mirrorworld.p2_base_bean.Thing_Editor_Dispatcher.Manage_user_intention(Thing_Editor_Dispatcher.java:28) at com.stepforward.mirrorworld.p4_view.Listener_Thing_List_Editor_View_Button.actionPerformed(Listener_Thing_List_Editor_View_Button.java:38) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6533) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6298) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466) at java.awt.Container.dispatchEventImpl(Container.java:2280) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79) at org.hibernate.loader.Loader.getResultSet(Loader.java:2117) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1900) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876) at org.hibernate.loader.Loader.doQuery(Loader.java:919) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306) at org.hibernate.loader.Loader.loadEntity(Loader.java:2204) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019) at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508) at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478) at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219) at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278) at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121) at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89) at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129) at org.hibernate.internal.SessionImpl.access$2600(SessionImpl.java:164) at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2696) at org.hibernate.internal.SessionImpl.get(SessionImpl.java:980) at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:290) at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170) at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69) at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:840) at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:822) at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:827) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:301) at com.sun.proxy.$Proxy72.merge(Unknown Source) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:517) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:515) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:500) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:283) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ... 51 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mirrorworld.person' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.Util.getInstance(Util.java:408) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2495) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1903) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2011) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) at com.sun.proxy.$Proxy79.executeQuery(Unknown Source) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70) ... 100 more
Spring集成Hibernate,使用JPA注解方式,新增数据无法提交
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>环境:</p> <p style="padding-left: 60px;">spring 3.1</p> <p style="padding-left: 60px;">hibernate 4.2.8 final </p> <p style="padding-left: 60px;">mysql 5.6</p> <p>问题描述:</p> <p style="padding-left: 30px;">调用controller的查询方法,可以正常返回数据</p> <p style="padding-left: 30px;">调用controller的创建方法,即:新增数据,控制台打印出了读取和修改序号表的sql,但是没有打印插入数据的sql,数据库表中也没有新增数据。</p> <p style="padding-left: 30px;">怀疑是spring控制的事务没有提交,但是排查了两三天,从网上找了各种方法,都没有解决问题。</p> <p style="padding-left: 30px;">请各位大侠拉小弟一把,实在是找不到事务为什么没有提交。</p> <p> </p> <p style="padding-left: 30px;">web.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;!-- 欢迎界面 --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- spring框架 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 上下文配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/applicationContext.xml, /WEB-INF/config/**/*.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- spring mvc --&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;!-- 拦截所有url --&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 回话有效期30分钟 --&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;!-- log4j日志 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- log4j日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/properties/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;</pre> <p> applicationContext.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 注解配置 --&gt; &lt;context:annotation-config /&gt; &lt;!--允许使用注解方式配置事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 对标注@PersistenceContext的类经行增强,引入代理后的EntityManager实例 --&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;!-- 对标注@Repository的类经行增强,将EntityManager异常转换为SpringDAO体系的异常 --&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt; &lt;!-- 属性文件 --&gt; &lt;context:property-placeholder location="/WEB-INF/properties/**/*.properties" /&gt; &lt;!-- 数据源 --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;!-- JPA 实体管理工厂 --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="ServicePlatform" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- JPA 事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> dispatcher-servlet.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 默认的注解映射的支持 --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 配置一下对json数据的转换 &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- 视图解析器 --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/view" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;!-- 对静态资源文件的访问 方案一 (二选一) --&gt; &lt;mvc:default-servlet-handler /&gt; &lt;!-- 对静态资源文件的访问 方案二 (二选一) &lt;mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">persistence.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="ServicePlatform" transaction-type="RESOURCE_LOCAL"&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">实体bean</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "bd_id") public class Identity implements Serializable { private static final long serialVersionUID = -8763611811485844772L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Column(length = 100) private String code; private Long value; @Column(length = 10) private String prefix; @Column(length = 10) private String suffix; @Column(length = 255) private String description; private Integer length; @Column(length = 30) private String creator; @Column(name = "create_date") private Timestamp createDate; @Column(length = 30) private String modifier; @Column(name = "modify_Date") private Timestamp modifyDate; private Boolean dr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Timestamp getModifyDate() { return modifyDate; } public void setModifyDate(Timestamp modifyDate) { this.modifyDate = modifyDate; } public Boolean getDr() { return dr; } public void setDr(Boolean dr) { this.dr = dr; } @Override public String toString() { return "Identity [id=" + id + ", code=" + code + ", value=" + value + ", prefix=" + prefix + ", suffix=" + suffix + ", description=" + description + ", length=" + length + ", creator=" + creator + ", createDate=" + createDate + ", modifier=" + modifier + ", modifyDate=" + modifyDate + ", dr=" + dr + "]"; } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">IdentityDaoImpl.java</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.entity.Identity; @Repository public class IdentityDaoImpl implements IIdentityDao { @PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public Identity create(Identity data) { em.persist(data); return data; } @Override public Identity retriver(String id) throws ServicePlatformException { Long pk = Long.valueOf(id); return em.find(Identity.class, pk); } @Override public Identity update(Identity data) throws ServicePlatformException { em.persist(data); return data; } @Override public void delete(String id) throws ServicePlatformException { em.remove(retriver(id)); } } </pre> <p> IdentityController.java</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.controller; import java.sql.Timestamp; import java.util.Calendar; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.dao.IIdentityDao; import com.lxl.bsp.identity.entity.Identity; @Controller @RequestMapping("identity") public class IdentityController { private static Log log = LogFactory.getLog(IdentityController.class); @Resource private IIdentityDao dao; @RequestMapping("retriver") @ResponseBody public Identity retriver(@RequestParam String id) throws ServicePlatformException { return dao.retriver(id); } @RequestMapping("create") @ResponseBody public Identity create() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("code" + i); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.create(data); log.debug(returnData); return returnData; } @RequestMapping("update") @ResponseBody public Identity update() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("1"); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.update(data); log.debug(returnData); return returnData; } @RequestMapping("delete") public void delete(@RequestParam String id) throws ServicePlatformException { dao.delete(id); } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">数据表结构DDL</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="sql">-- ---------------------------- -- Table structure for bd_id -- ---------------------------- DROP TABLE IF EXISTS `bd_id`; CREATE TABLE `bd_id` ( `id` bigint(30) NOT NULL, `code` varchar(100) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `creator` varchar(30) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `dr` tinyint(1) DEFAULT NULL, `length` int(11) DEFAULT NULL, `modifier` varchar(30) DEFAULT NULL, `modify_Date` datetime DEFAULT NULL, `prefix` varchar(10) DEFAULT NULL, `suffix` varchar(10) DEFAULT NULL, `value` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">附件中是项目压缩包,只要电脑上安装了数据库,解压即可运行,数据库名称是osd</p> <p> </p> </div>
Spring data中使用懒加载时,报错could not initialize proxy - no Session的解决方案?
今天我在使用懒加载的时候,eclipse一直报错,报错内容为:failed to lazily initialize a collection of role,could not initialize proxy - no Session。 网上找到的解决方法主要有三种: 1.懒加载改为积极加载,这个方法确实有效,但严重影响了效率,我查询一个sql语句花了好几分钟都没出结果。 2.在web.xml中配置OpenSessionInViewFilter或OpenEntityManagerInViewFilter,我都试过了,没有用; 3.在类或者方法上添加@Transactional,我都加了,也没有用; 请问有没有人知道该怎么解决 我的代码如下 web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jjyc</display-name> <welcome-file-list> <welcome-file>/WEB-INF/pages/index.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- session --> <filter> <filter-name>hibernateFilter</filter-name> <filter-class> org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> <init-param> <!-- 指定org.springframework.orm.jpa.LocalEntityManagerFactoryBean在spring配置文件中的名称,默认值为entityManagerFactory 如果LocalEntityManagerFactoryBean在spring中的名称不是entityManagerFactory,该参数一定要指定,否则会出现找不到entityManagerFactory的例外 --> <param-name>entityManagerFactoryBeanName</param-name> <param-value>entityManagerFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> <url-pattern>*.js</url-pattern> <url-pattern>*.gif</url-pattern> <url-pattern>*.jpg</url-pattern> <url-pattern>*.jpeg</url-pattern> <url-pattern>*.png</url-pattern> <url-pattern>*.ico</url-pattern> <url-pattern>*.zip</url-pattern> <url-pattern>*.rar</url-pattern> </servlet-mapping> <servlet> <servlet-name>SpringMVCLesson</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVCLesson</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <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> </web-app> ``` ![图片说明](https://img-ask.csdn.net/upload/201906/22/1561203761_304383.png) ![图片说明](https://img-ask.csdn.net/upload/201906/22/1561203774_481870.png)
spring boot 与jpa结合的过程中出现问题,但刚接触不知道问题在哪,麻烦大神指点,十分感谢
``` @Controller public class RedisController { @Autowired private RedisStatusService redisStatusService; @RequestMapping("") public String index(HttpServletResponse response) { //重定向到 /index return response.encodeRedirectURL("/index"); } @RequestMapping(value = "/showredisstutas" , method = RequestMethod.GET) public String addCourse(HttpServletResponse response, HttpSession session,@RequestParam(value = "ipadd") String ipadd, @RequestParam(value = "port") String port){ Iterable<RedisStatus> list=redisStatusService.getRedisStatusInfo(ipadd,port); session.setAttribute("statuslist",list); return response.encodeRedirectURL("/showRedisStatus"); } } ``` ```public class RedisStatusService { /* @Resource RedisStatusDao redisStutasDao; @Resource RedisPortInfoDao redisPortInfoDao;*/ @Autowired private RedisPortInfoDao redisPortInfoDao; @Autowired private RedisStatusDao redisStutasDao; public Iterable<RedisStatus> getRedisStatusInfo(String ip,String port){ Iterable<RedisStatus> list=null; try { RedisPortInfo rpi=redisPortInfoDao.findByRedis_ipAndRedis_port(ip,port); if(rpi!=null){ list = new ArrayList<RedisStatus>(); list = redisStutasDao.findByRedis_idOrderByRecoder_timeDesc(rpi.getRedis_port_id()); }else{ list=null; } }catch (Exception ee){ list=null; } return list; } } ``` ```public interface RedisPortInfoDao extends CrudRepository<RedisPortInfo, String> { public RedisPortInfo findByRedis_ipAndRedis_port(String redis_ip,String redis_port); } ``` ``` @Entity @Table(name = "redis_port_info") public class RedisPortInfo { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "redis_port_id") private int redis_port_id; @Column(name = "redis_ip") private String redis_ip; @Column(name = "redis_port") private int redis_port; @Column(name = "redis_name") private String redis_name; @Column(name = "slowlog_lastid") private int slowlog_lastid; public int getRedis_port_id() { return redis_port_id; } public void setRedis_port_id(int redis_port_id) { this.redis_port_id = redis_port_id; } public String getRedis_ip() { return redis_ip; } public void setRedis_ip(String redis_ip) { this.redis_ip = redis_ip; } public int getRedis_port() { return redis_port; } public void setRedis_port(int redis_port) { this.redis_port = redis_port; } public String getRedis_name() { return redis_name; } public void setRedis_name(String redis_name) { this.redis_name = redis_name; } public int getSlowlog_lastid() { return slowlog_lastid; } public void setSlowlog_lastid(int slowlog_lastid) { this.slowlog_lastid = slowlog_lastid; } } ``` 以下是报错信息 ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.service.RedisStatusService com.example.controller.RedisController.redisStatusService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisStatusService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.dao.RedisPortInfoDao com.example.service.RedisStatusService.redisPortInfoDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPortInfoDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.service.RedisStatusService com.example.controller.RedisController.redisStatusService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisStatusService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.dao.RedisPortInfoDao com.example.service.RedisStatusService.redisPortInfoDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPortInfoDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisStatusService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.dao.RedisPortInfoDao com.example.service.RedisStatusService.redisPortInfoDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPortInfoDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.dao.RedisPortInfoDao com.example.service.RedisStatusService.redisPortInfoDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPortInfoDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisPortInfoDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! Caused by: org.springframework.data.mapping.PropertyReferenceException: No property redis found for type RedisPortInfo! ``` 麻烦大神帮忙找出问题
SpringMVC + Hibernate + JPA 在linux不能启动,windows下可以
同样的配置,依赖包,Tomcat,Myeclipse, 在windows下完全正常运行,和JUnit测试 在linux下不能启动,但是可以JUnit测试 ========== 异常 (启动Tomcat的时候出现异常) ========== ``` 十二月 03, 2016 1:46:23 上午 org.apache.catalina.core.ApplicationContext log 严重: StandardWrapper.Throwable java.lang.NoSuchMethodError: org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.registerIfNotAlreadyRegistered(Lorg/springframework/beans/factory/support/AbstractBeanDefinition;Lorg/springframework/beans/factory/support/BeanDefinitionRegistry;Ljava/lang/String;Ljava/lang/Object;)V at org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.registerBeansForRoot(JpaRepositoryConfigExtension.java:166) at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:80) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:352) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:143) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:336) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:246) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:270) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4913) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1107) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1841) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) 十二月 03, 2016 1:46:23 上午 org.apache.catalina.core.StandardContext loadOnStartup 严重: Servlet [dispatcher] in web application [/CDC_center] threw load() exception java.lang.NoSuchMethodError: org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.registerIfNotAlreadyRegistered(Lorg/springframework/beans/factory/support/AbstractBeanDefinition;Lorg/springframework/beans/factory/support/BeanDefinitionRegistry;Ljava/lang/String;Ljava/lang/Object;)V at org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.registerBeansForRoot(JpaRepositoryConfigExtension.java:166) at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:80) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:352) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:143) at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:336) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:246) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:270) at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:524) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4913) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1107) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1841) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) 十二月 03, 2016 1:46:23 上午 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deployment of web application directory /home/lee/opt/apache-tomcat-8.5.8/webapps/CDC_center has finished in 1,645 ms ``` ========== Java配置 ========== ``` @Configuration @ComponentScan("com.unbcomm.dao") @EnableJpaRepositories(basePackages = "com.unbcomm.dao") // <== 上边的异常是这个注解引发的 @EnableTransactionManagement public class DataSourceConfig { @Bean public DataSource dataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/CDC_center"); ds.setUsername("root"); ds.setPassword("1234"); return ds; } // JPA Hibernate @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); adapter.setShowSql(true); adapter.setGenerateDdl(false); return adapter; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean(); emfb.setDataSource(dataSource); emfb.setJpaVendorAdapter(jpaVendorAdapter); emfb.setPackagesToScan("com.unbcomm.pojo"); return emfb; } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } } ``` ========== JUnit 测试 (这个测试可以正常运行) ========== ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { DataSourceConfig.class }) public class Test_JpaGroupDAO { @Autowired private GroupRepository simpleRepository; @Test public void findAll() { List<Group> gList = simpleRepository.findAll(); for(Group g : gList) System.out.println(g.getName()); } } ```
spring boot service接口问题
报错:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'girlController': Unsatisfied dependency expressed through field 'girlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'girlRepository': Post-processing of merged bean definition failed; nested exception is java.lang.NoSuchMethodError: javax.persistence.PersistenceContext.synchronization()Ljavax/persistence/SynchronizationType; GirlRepository: import org.springframework.data.jpa.repository.JpaRepository; public interface GirlRepository extends JpaRepository<Girl, Integer> { } GirlController: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class GirlController { @Autowired private GirlRepository girlRepository; @GetMapping(value = "/girls") public List<Girl> girlList(){ return girlRepository.findAll(); } } 求大神帮忙看看哪里的问题啊?
Maven的pom.xml第一行报错,显示未知错误,哪位大佬能帮忙解决下,不胜感激!
问题rt 代码如下: ![图片说明](https://img-ask.csdn.net/upload/201906/12/1560350057_455880.png) ![图片说明](https://img-ask.csdn.net/upload/201906/12/1560350062_430379.png) ``` <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- 从spring-boot-starter-parent继承版本号 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.manning</groupId> <artifactId>readinglist</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Reading List</name> <description>Reading List Demo</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-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <!-- maven构建插件 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ```
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
相关热词 c# 输入ip c# 乱码 报表 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件
立即提问