hibernate保存数据报错

org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into ORC_T_BUSINESS_TRACK (BUSI_NUM, BUSI_TYPE, CREATE_DATE, CREATE_USER_NAME, CREATE_USER_NUM, REMARK, ID) values (?, ?, ?, ?, ?, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:643)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:104)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:516)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:394)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.bsteel.shdc.service.OrcTBusinessTrackServiceImpl$$EnhancerByCGLIB$$416c9ca9.saveOrcTBusinessTrack()
at com.bsteel.shdc.bankservice.finance.redeem.controller.AuditController.signaTure1(AuditController.java:642)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1221)
at com.bsteel.shdc.manager.permission.filter.AuthFilter.doFilter(AuthFilter.java:101)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:945)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:262)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:512)
... 47 more
Caused by: java.sql.BatchUpdateException: ORA-01401: inserted value too large for column

at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:345)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10844)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 56 more

[color=red][/color]

3个回答

1.插入的数据中,有的字段为null,但是数据库表限制该字段不能为null
[code="java"] Could not execute JDBC batch update; SQL [insert into ORC_T_BUSINESS_TRACK (BUSI_NUM, BUSI_TYPE, CREATE_DATE, CREATE_USER_NAME, CREATE_USER_NUM, REMARK, ID) values (?, ?, ?, ?, ?, ?, ?)]; constraint [null];[/code]

2.批量更新数据时,有些数据的字段值超过了数据库表定义的字段最大值,要么扩大该字段的值,要么对插入的数据进行校验
[code="java"]Caused by: java.sql.BatchUpdateException: ORA-01401: inserted value too large for column[/code]

sadasafsdfdsf
sadasafsdfdsf 对 就是一个 字段太长了 是USER对象里面的一个字段本来是ID保存成Name了然后在写入数据库时长度过大 不知道谁动了项目里的字段了 奶奶的
5 年多之前 回复

Could not execute JDBC batch update; SQL [insert into ORC_T_BUSINESS_TRACK (BUSI_NUM, BUSI_TYPE, CREATE_DATE, CREATE_USER_NAME, CREATE_USER_NUM, REMARK, ID) values (?, ?, ?, ?, ?, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException

没有代码 只能从你上面报出的异常来 推测
1.可能你数据库里面的字段设置不能为空 但是你往做句库做动作的时候 这个字段上的值是空的

2.可能是配置文件设置了关联,数据却没有关联造成的,只要数据正确就没有问题。

另外,造成这个原因的还可能是数据库的驱动jar包不支持。
3.因为Hibernate Tools(或者Eclipse本身的Database Explorer)生成*.hbn.xml工具中包含有catalog="***"(*表示数据库名称)这样的属性,将该属性删除就可以了
4.估计是你的列名里面有关键字的原因吧,命名列的时候不要单独使用date,ID...这种关键字

其实吧,出现异常,定位的话只要看Caused by后面的就行了。。
Caused by: java.sql.BatchUpdateException: ORA-01401: inserted value too large for column
有个字段的值太大了。。就这么简单。。目测是某个字符串长度没给够,自己检查下数据库表和hibernate配置文件吧

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
hibernate 配置文件报错
![图片说明](https://img-ask.csdn.net/upload/201701/03/1483440537_361655.png) 之前是create没问题,换成update就报错,但还是能执行。不过第二天数据库就报10061错误,不清楚问题到底出在哪里。下面是我的全部代码。 配置文件: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">root</property> <property name="connection.url">jdbc:mysql://localhost:5656/mysql</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.password">123456</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="Students.hbm.xml"/> </session-factory> </hibernate-configuration> 测试文件: import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Date; public class Studentstest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init() { //创建配置对象 Configuration config = new Configuration().configure(); //创建服务注册对象 // ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); //创建会话工厂对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); sessionFactory = config.buildSessionFactory(serviceRegistry); //会话对象 session = sessionFactory.openSession(); //开启事务 transaction = session.beginTransaction(); } @After public void destory() { transaction.commit(); //提交事务 session.close(); //关闭会话 sessionFactory.close(); //关闭会话工厂 } @Test public void testSaveStudents() {//增加 //生成学生对象 Students s = new Students(); s.setSname("POLY Ma"); s.setBirthday(new Date()); s.setAddress("Hong Kong"); s.setGender("M"); session.save(s); //保存对象进入数据库 } @Test public void search(){//查找 Students s=session.get(Students.class,1);//1 is primary key System.out.print(s); } @Test public void update(){//修改 Students s=session.get(Students.class,2);//look on s.setAddress("Hang Zhou"); session.update(s); } @Test public void delete(){//删除 Students s=session.get(Students.class,1); session.delete(s); } } 映射文件: <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Students" table="students"> <id name="sid" type="int"> <column name="sid"/> <generator class="native"/> </id> <property name="sname" type="java.lang.String"> <column name="sname"/> </property> <property name="gender" type="java.lang.String"> <column name="gender"/> </property> <property name="birthday" type="date"> <column name="birthday"/> </property> <property name="address" type="java.lang.String"> <column name="address"/> </property> </class> </hibernate-mapping> 主体: import java.util.Date; /** * Created by tcxd on 2016/12/28. */ public class Students { private int sid; //学号 private String sname; //姓名 private String gender; //性别 private Date birthday; //出生日期 private String address; //地址 public Students() { } public Students(int sid, String sname, String gender, Date birthday, String address) { this.sid = sid; this.sname = sname; this.gender = gender; this.birthday = birthday; this.address = address; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } @Override public String toString() { return "Students{" + "sid=" + sid + ", sname='" + sname + '\'' + ", gender='" + gender + '\'' + ", birthday=" + birthday + ", address=" + address + '}'; } }
测试hibernate框架自动建表并保存数据,没报错,但数据只保存了一部分
![图片说明](https://img-ask.csdn.net/upload/201603/23/1458711095_350255.jpg)
hibernate 保存对象到数据库
Illegal attempt to associate a collection with two open sessions 报错
springboot JPA保存报错
用户类 ``` @Entity @SecondaryTable(name="sys_user_extend") @GenericGenerator(name = "jpa-uuid", strategy = "uuid") public class SysUser implements UserDetails { /** * */ private static final long serialVersionUID = 1L; public SysUser() { } public SysUser(String loginName, String password) { super(); this.loginName = loginName; this.password = password; } @Id @GeneratedValue(generator = "jpa-uuid") private String id; @Column(unique=true ,nullable = false) private String loginName; @Column(nullable = false) private String password; @Column(unique=true ,nullable = false) private String name; @Column(unique=true) private String email; @Column(unique=true) private String phone; @Column private String remark; @Column private String lastLoginTime; @Column(nullable = false) private String isActive = "true"; @Column(table="sys_user_extend") private String level; @Column(table="sys_user_extend") private String currentExperience; @Column(table="sys_user_extend") private String totalExperience; @ManyToMany(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER) private List<SysRole> roles; @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); List<SysRole> roles = this.getRoles(); for (SysRole role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } //省略get、set方法 } ``` ``` public interface SysUserRepository extends JpaRepository<SysUser, Long> { SysUser findByLoginName(String loginname); SysUser findByPhone(String phone); SysUser findByEmail(String email); } ``` controller层的添加方法 ``` //添加 @ResponseBody @RequestMapping(value="/user",method=RequestMethod.POST) public Object post(@RequestBody SysUser user){ BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String encodedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(encodedPassword); userserivce.saveUser(user); return user; } ``` ![数据库用户表](https://img-ask.csdn.net/upload/201909/24/1569312948_464905.png) ![数据库用户扩展信息表](https://img-ask.csdn.net/upload/201909/24/1569313009_372653.png) 报错信息: > org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.sakuraSmiles.alpha.security.model.SysUser[\"authorities\"])" 测试json {"loginName":"test123","name":"测试","password":"123456","level":"5"} 项目使用了spring security,通过postman模拟请求,debug跟了下发现controller层的user是能拿到我传的对象的,但是里面也没有authorities字段。网上找了好久也没看到有跟我这个类似的,请问有人碰到过相似的问题吗?或者有大佬帮忙看一看吗? 感谢1楼和3楼大牛的解答帮助,十分感谢两位的帮助。分想要两位都给的,没办法只能选择一个采纳,就先给了1楼。问题已经解决了,定位到就是如3楼大牛所说,因为实现UserDetails 接口会有getAuthorities方法,在进行序列化时发现有带getXX开始的方法会自动去找XX的属性, 但是发现并没这个属性,所以报错。网上搜索了一下jpa有没有能够让系统能够忽视这个get方法的注释,在getAuthorities方法上面添加了@JsonIgnore就执行save不会报错了,目前没看出对于其他地方有没有影响。 ``` @Override @JsonIgnore public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); List<SysRole> roles = this.roles; for (SysRole role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } ``` ![图片说明](https://img-ask.csdn.net/upload/201909/24/1569316069_705652.png)
Help!求助:Hibernate整合JPA后测试增、删、改、查报错
小弟新手,刚开始学习开发,最近出现一个问题,求各位大神指教,小弟万分感谢! 在做的是一个体系分级,已经实现了针对一级表的增、删、改、查,这里是正常的。 但是在做二级表时报错。二级表与一级表的区别只是:增加了一级主键ID。 下面图片是代码: ![图片说明](https://img-ask.csdn.net/upload/201709/01/1504227247_38118.png) ![图片说明](https://img-ask.csdn.net/upload/201709/01/1504227261_327178.png) ![图片说明](https://img-ask.csdn.net/upload/201709/01/1504227273_19660.png) ![图片说明](https://img-ask.csdn.net/upload/201709/01/1504227284_575148.png) 下面是数据表:标红框的地方是上级ID标识。 ![图片说明](https://img-ask.csdn.net/upload/201709/01/1504227455_774857.png) 下面是报错信息: 1. 保存报错: 非法参数异常发生 javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.byebook.bean.study.CyYw1KP2.kpID 非法参数异常发生 Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.byebook.bean.study.CyYw1KP2.kpID 对象不是声明类的实例。 Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class 2. 查询报错: ① javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID ② Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID 3. 删除报错: javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID ① Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID ② Caused by: java.lang.IllegalArgumentException: argument type mismatch 4. 更新报错: ① javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID ② Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.byebook.bean.study.CyYw1KP2.kp1ID ③ Caused by: java.lang.IllegalArgumentException: argument type mismatch 求各位大神指教,小弟再次万分感谢!!!
使用注解生成的uuid.hex 调用save()保存对象不发语句也不报错
``` @Id @GenericGenerator(name="systemUUID",strategy="uuid") @GeneratedValue(generator="systemUUID") @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return this.id; } ```实体类的部分代码如上,在调用save方法的时候不报错也不保存,数据库中没有数据。平时主键使用int类型,自动增长,调用save就可以,现在公司要用varchar作为主键,调用save方法不报错,也不报错,我快崩溃了,该怎么办
java 保存clob类型数据是报错怎么解决
实体类型: ``` /** *方法: 取得java.lang.Clob *@return: java.lang.Clob 学习内容 */ @Column(name ="STUDY_CONTENT",nullable=true,length=4000) public java.sql.Clob getStudyContent() { return studyContent; } /** *方法: 设置java.lang.Clob *@param: java.lang.Clob 学习内容 */ public void setStudyContent(java.sql.Clob studyContent) { this.studyContent = studyContent; } ``` 数据库字段: ![图片说明](https://img-ask.csdn.net/upload/201611/15/1479196609_159328.png) 报错信息: ``` [org.jeecgframework.core.common.exception.GlobalExceptionResolver]全局处理异常捕获: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'djIntStudyEntity' on field 'studyContent': rejected value [<p>学习内容</p>]; codes [typeMismatch.djIntStudyEntity.studyContent,typeMismatch.studyContent,typeMismatch.java.sql.Clob,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [djIntStudyEntity.studyContent,studyContent]; arguments []; default message [studyContent]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Clob' for property 'studyContent'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.sql.Clob] for property 'studyContent': no matching editors or conversion strategy found] at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:818) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:367) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.jeecgframework.core.aop.GZipFilter.doFilter(GZipFilter.java:49) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:140) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:119) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) ```
java hibernate级联保存
![![图片说明](https://img-ask.csdn.net/upload/201501/18/1421582430_407257.png)图片说明](https://img-ask.csdn.net/upload/201501/18/1421582416_713571.png) 我用的是级联保存,已保存就报这样的错,实体类user从数据库中查出来的,求大神解决
hibernate Spring save指令无法保存
使用了save指令 但是控制台没有输出insert语句 也没有报错 没有保存数据 ```@Entity public class Payroll{ @Id @GeneratedValue private long pid; private long sid; //结账日期 private Timestamp date; //累结 private double totalSum; //结余 private double balance; //伙食费用 private double boardWages; //扣款 private double deduct; //欠款 private double debt; ///预支 private double advance; //薪水细则 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="pid") private List<PayrollRow> payrollRow = new ArrayList<PayrollRow>(); //省略GETTER SETTER } ``` ``` @Entity public class PayrollRow { @Id @GeneratedValue private long prid; private String style_number; private String process; private int count; private double cost; private double amount; // } ``` DAO层 ``` @Repository public class PayrollDAOImpl implements PayrollDAO{ @Autowired SessionFactory sessionFactory; public boolean save(Payroll p) { // TODO Auto-generated method stub try { System.out.println("info"+sessionFactory.getCurrentSession().save(p)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return false; } return true; } public boolean saveRow(PayrollRow pr){ // TODO Auto-generated method stub try { System.out.println("info"+sessionFactory.getCurrentSession().save(pr)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return false; } return true; } } ``` service层 ``` @Service @Transactional public class PayrollServiceImpl implements PayrollService { @Autowired PayrollDAOImpl payrollDAO ; public boolean save(Payroll payroll){ List<PayrollRow> pwl = payroll.getPayrollRow(); for (int i = 0;i<pwl.size();i++) { payrollDAO.saveRow(pwl.get(i)); System.out.println("info "+i); } return payrollDAO.save(payroll); } } ``` 配置文件 ``` <!-- 支持注解 --> <mvc:annotation-driven /> <!--自动装配DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:default-servlet-handler /> <!-- 设置自动扫描的路径,用于自动注入bean 这里的路径与自己的项目目录对应--> <!-- 扫描controller路由控制器 --> <context:component-scan base-package="pres.uiiooo.controller" /> <context:component-scan base-package="pres.uiiooo.daoimpl,pres.uiiooo.serviceimpl" /> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="suffix" value=".jsp" /> <!-- 视图文件类型 --> <property name="prefix" value="/WEB-INF/views/" /> <!-- 视图文件的文件夹路径 --> </bean> </beans> ``` ``` <!-- JNDI(通过Tomcat)方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 这里class可以使用不同的驱动--> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc_driverClassName}" /> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="current_session_context_class">thread</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <!-- 此处与entity实体路径对应 --> <value>pres.uiiooo.model</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 其他的DAO层save是可用的 但是这个不行 应该是涉及到事务管理配置 还有一对多配置方面的问题 求大佬解决 谢谢谢谢了!!!
如何通过hibernate存取日期
比如我要将表单中的2011-08-12这个日期存入数据库。我的实体该将这字段映射成什么类型?我将它映射成Date。可是保存时后台直报错。大家都是怎样做的?我已经弄了一天了,还是不行。我用的框架是spring mvc hibernate mysql。
hibernate 一对多的保存问题,望赐教
one public class DCompany extends BaseEntity { /** * */ private static final long serialVersionUID = 2472916124848152035L; /** * 公司标识 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") private String comId; /** * 公司名称 */ private String comName; /** * 用户信息 */ @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "comId") private List<DUser> users; /** * 公司地址 */ private String comAddress; /** * 公司经营类别 */ private String comType; /** * 公司简介 */ private String comIntro; /** * 公司电话 */ private String comTel; /** * 增加时间 */ private String comCreateDate; many public class DUser extends BaseEntity { /** * */ private static final long serialVersionUID = -7733922431721279323L; /** * 用户标识 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") private String userId; /** * 姓名 */ private String userName; /** * 所属公司信息 */ @ManyToOne @JoinColumn(name = "comId") private DCompany company; /** * 性别标识M.男F.女 */ private String userSex; /** * 密码 */ private String userPass; /** * Email */ private String userEmail; /** * 电话 */ private String userTel; /** * qq */ private String userQq; /** * 是否冻结 0冻结 1正常 */ private Integer userEnable; /** * 创建时间 */ private Timestamp userCreateDate; 现在数据库里的数据都是空的,没有记录,我想实现的是DCompany 和DUser一起保存在数据库中 比如jsp页面文本框信息如下: 公司名: 公司地址: 公司电话: 姓名: 性别: QQ: 也就是页面上一次录入DCompany 实体信息与DUser实体信息,然后一点保存,分别把DCompany 信息保存到DCompany 表,DUser信息保存到DUser表中 我的测试代码是这么写的: DCompany company = new DCompany(); company.setComName("北京时间有限公司"); company.setComAddress("朝阳区酒仙桥1号"); company.setComIntro("介绍信息写这里"); company.setComTel("010-38782121"); company.setComType("test"); DUser user = new DUser(); user.setUserName("test"); user.setUserEmail("test@188.com"); user.setUserPass("123afb"); user.setUserEnable(1); user.setUserSex("M"); user.setUserTel("13811112121"); user.setUserQq("21232221"); List list = new ArrayList(); list.add(user); company.setUsers(list); companyService.saveCompany(company); 可是保存不进去,DUser表里有comId,这样以来如果没有先保存DCompany 信息是不会有comId的,报错 object references an unsaved transient instance - save the transient instance before flushing: org.wdj.base.entity.DUser; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: org.wdj.base.entity.DUser 请问 该如何做呢,谢谢
hibernate的session.save()为什么没有执行
User 是一个有id username passwrod的类 hb.cfg.xml <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 先配置数据库链接信息 --> <property name = "connection.driver_class">com.mysql.jdbc.Driver</property> <property name = "connection.url">jdbc:mysql://localhost:3306/dxlin</property> <property name = "connection.username">root</property> <property name = "connection.password">duanlin113</property> <property name="javax.persistence.validation.mode">none</property> <!-- 数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource = "com/dxlin/pojo/person.hbm.xml"/> </session-factory> </hibernate-configuration> User.hbm.xml <?xml version="1.0" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package = "com.dxlin.pojo"> <class name = "com.dxlin.pojo.User" table = "User"> <id name = "id"> <!-- 主键生成策略 --> <generator class="native" column = "id"></generator> </id> <property name="username" column = "username"/> <property name="password" column = "password"/> </class> </hibernate-mapping> Test 类 package com.dxlin.hibtest; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.dxlin.pojo.User; public class Test { public static void main(String args[]) { System.out.println("1"); //1.新建立Configuration对象 Configuration cfg = new Configuration(); cfg.configure("hb.cfg.xml"); System.out.println("2"); //2.通过Configuration新建sessionFactory对象 ServiceRegistry registry = new StandardServiceRegistryBuilder() .applySettings(cfg.getProperties()) .build(); SessionFactory sf = cfg.buildSessionFactory(registry); System.out.println("3"); //3.通过sessionFactory得到session Session session = sf.openSession(); System.out.println("4"); //4.通过session对象得到Transaction对象 Transaction tx = session.beginTransaction(); System.out.println("5"); //保存数据 User user = new User(); user.setUsername("DL2"); user.setPassword("002"); session.save(user); System.out.println("6"); //提交事务 tx.commit(); System.out.println("7"); //关闭session session.close(); System.out.println("8"); } } 代码不报错,运行为 ![图片说明](https://img-ask.csdn.net/upload/201710/15/1508064451_919348.png)
新手学习hibernate出错
myeclipse下保存操作,可以把数据保存到数据库,但是启动tomcay后就会在控制台报错如下:java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO),如何解决?网上查了好久还是没有解决,密码和用户名没有错误。
慕课网案例 新手Hibernate配置问题,单表操作
搞了两天了,一直卡在这。百度了好多也没找到解决方案,希望大家帮我看看。 **编程环境** * Eclipse Neon.3 Release (4.6.3) * hibernate(5.3.0) * JDBC8.0.11 * MySQL5.6 **报错信息** ``` Apr 23, 2018 5:06:42 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.3.0.CR1} Apr 23, 2018 5:06:42 PM org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found Apr 23, 2018 5:06:42 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.2.Final} Apr 23, 2018 5:06:42 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time. Apr 23, 2018 5:06:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) Apr 23, 2018 5:06:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC] Apr 23, 2018 5:06:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} Apr 23, 2018 5:06:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Apr 23, 2018 5:06:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Apr 23, 2018 5:06:43 PM org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect Apr 23, 2018 5:06:44 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@24be2d9c] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. ``` **项目结构** ![图片说明](https://img-ask.csdn.net/upload/201804/23/1524474801_956742.png) **项目内容** hibernate.cfg.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 1.设置四本一言 --> <!-- 驱动,连接URL,用户名,密码,方言 --> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="current_session_context_class">thread</property> <!-- 2.全局配置信息 --> <!--是否显示SQL语句 --> <property name="show_sql">true</property> <!--是否格式化SQL语句 --> <property name="format_sql">true</property> <!--执行DDL的类别: create:每次都删除新建 update:存在就修改,不存在就新建 --> <property name="hbm2ddl.auto">update</property> <!--3.加载配置文件 --> <!--基于xml映射文件: 映射文件加载。路径 --> <mapping resource="Student.hbm.xml"/> <!-- <mapping class="Students"/> --> </session-factory> </hibernate-configuration> ``` Student.java ``` import java.util.Date; public class Student { private int sId; private String sName; private String gender; private Date birthday; private String address; public Student() { } public Student(int sId, String sName, String gender, Date birthday, String address) { this.sId = sId; this.sName = sName; this.gender = gender; this.birthday = birthday; this.address = address; } @Override public String toString() { return "Student [sId=" + sId + ", sName=" + sName + ", gender=" + gender + ", birthday=" + birthday + ", address=" + address + "]"; } public int getsId() { return sId; } public void setsId(int sId) { this.sId = sId; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } ``` Student.test.java ``` import java.util.Date; import org.hibernate.*; import org.hibernate.cfg.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StudentTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void Init() { // 1.加载配置文件 Configuration configuration = new Configuration().configure(); // 2.创建Session工厂 SessionFactory factory = configuration.buildSessionFactory(); // 3.创建Session对象 Session session = factory.openSession(); // 4.开启事务 transaction = session.beginTransaction(); } @Test public void testSaveStudents() { //生成对象 Student student=new Student(1,"张三丰","男",new Date(),"武当山"); //保存对象进数据库 session.save(student); } @After public void destory() { //提交事务 transaction.commit(); //关闭session会话 session.close(); //关闭sessionFactory会话工厂 sessionFactory.close(); } } ``` Student.hbm.xml ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Apr 21, 2018 5:32:53 PM by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="Student" table="STUDENT"> <id name="sId" type="int" access="field"> <column name="SID" /> <generator class="assigned" /> </id> <property name="sName" type="java.lang.String" access="field"> <column name="SNAME" /> </property> <property name="gender" type="java.lang.String"> <column name="GENDER" /> </property> <property name="birthday" type="java.util.Date"> <column name="BIRTHDAY" /> </property> <property name="address" type="java.lang.String"> <column name="ADDRESS" /> </property> </class> </hibernate-mapping> ``` Navicat中显示,仅生成了表。 ![图片说明](https://img-ask.csdn.net/upload/201804/23/1524475414_34908.png)
Hibernate4 org.hibernate.QueryException异常问题
各位大侠好,项目一直报错"org.hibernate.QueryException: could not resolve property: u_phone of: com.wanshang.po.Users",我仔细检查po类和映射文件,也没发现错误,请问各位大侠,这个问题是哪里错了?下面是各配置文件: ## Users.java ``` public class Users { private int id; private String name; private String phone; private String password; private String paypassword = "*"; private String usertype = "customer"; private float point = 0; public Users(){} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPaypassword() { return paypassword; } public void setPaypassword(String paypassword) { this.paypassword = paypassword; } public String getUsertype() { return usertype; } public void setUsertype(String usertype) { this.usertype = usertype; } public float getPoint() { return point; } public void setPoint(float point) { this.point = point; } } ``` ## Users.hbm.xml ``` <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.wanshang.po.Users" table="usersInfo"> <!-- 用户编号 --> <id name="id" column="u_id"> <generator class="identity" /> </id> <!-- 用户姓名 --> <property name="name" column="u_name" /> <!-- 用户手机 --> <property name="phone" column="u_phone" /> <!-- 用户密码 --> <property name="password" column="u_password" /> <!-- 用户支付密码 --> <property name="paypassword" column="u_paypassword" /> <!-- 用户类型 --> <property name="usertype" column="u_usertype" /> <!-- 用户积分 --> <property name="point" column="u_point" /> </class> </hibernate-mapping> ``` ## hibernate.cfg.xml ``` <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="myeclipse.connection.profile">mysql</property> <!-- 数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 数据库驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库链接 --> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/wanshang</property> <!-- 数据库用户名 --> <property name="connection.username">root</property> <!-- 数据库密码 --> <property name="connection.password"></property> <!-- 数据库连接池最大连接数 --> <property name="connection.pool_size">2000</property> <!-- 自动建表 --> <property name="hbm2ddl.auto">update</property> <!-- 打印SQL语句 --> <property name="show_sql">true</property> <!-- 映射 --> <mapping resource="com/wanshang/po/Users.hbm.xml" /> </session-factory> </hibernate-configuration> ``` ## 报错时经常会指向这个方法,代码如下: ``` /*通过字段集合查找*/ public Users findByMap(Map<String, String> params) { // TODO Users users = new Users(); //生成Session实例 Session session = HibernateUtil.getSession(); try{ Criteria criteria = session.createCriteria(Users.class); //遍历Map Set<String> key = params.keySet(); for(Iterator it = key.iterator();it.hasNext();){ String k = (String) it.next(); //保存key criteria.add(Restrictions.eq(k, params.get(k)));//eq是等于,gt是大于,lt是小于,or是或 System.out.println(k+":"+params.get(k)); } users = (Users) criteria.list().get(0); }catch(Exception e){ e.printStackTrace(); }finally{ //关闭Session实例 HibernateUtil.closeSession(session); return users; } } ``` ## 下面是数据库截图: ![图片说明](https://img-ask.csdn.net/upload/201610/21/1477037855_873577.jpg)
数据库没加唯一约束的时候,代码不报错,加上之后验证的时候,可以根据异常简单的try catch处理吗
ERROR 2015-12-02 11:57:55,110 [http-bio-8080-exec-20](JDBCExceptionReporter.java:78) - ORA-00001: 违反唯一约束条件 (SCOTT.SYS_C0011574) ERROR 2015-12-02 11:57:55,110 [http-bio-8080-exec-20](JDBCExceptionReporter.java:78) - ORA-00001: 违反唯一约束条件 (SCOTT.SYS_C0011574) ERROR 2015-12-02 11:57:55,110 [http-bio-8080-exec-20](AbstractFlushingEventListener.java:301) - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) try catch语句是这样的 try { bankBManager.addBankBEntity(bankB); request.setAttribute("jsons", "{\"success\":true,\"msg\":\"保存成功\"}"); } catch (Exception e) { request.setAttribute("jsons", "{\"success\":true,\"msg\":\"数据重复,请重新输入\"}"); }
hibernate3 的多对一的外键更新问题!
[code="ruby"] public class SysModel extends BaseEntity<SysModel> { @ManyToOne(cascade = { CascadeType.MERGE }) @JoinColumn(name = "PARENT_ID") private SysModel sysModel; ....... } [/code] 映射文件大概如此, 有一个自关联字段。 在操作的时候,遇到一个问题,当此字段为 null 的时候,我可以保存,但是不能更新,报错: Hibernate: update SYS_MODEL set DELETE_FLAG=?, MODEL_NAME=?, ORDER_ID=?, remark=?, PARENT_ID=?, url=?, version=? where id=? 2008-09-10 09:55:31,906 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] - <Could not synchronize database state with session> org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.sctt.system.sys.model.bean.SysModel at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:219) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397) at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:78) 也就是说,PARENT_ID=? 为 NULL 。我基本知道错误原因。 但是,我的本条数据,确实 没有外键呀, sysModel = null; 如何才能更新 这样的数据呢?往高人回答。
hibernate 求各位大神 帮忙看一下
我做的一个Hibernate 一对多 多对一的 保存和读取操作 保存 没问题 但是 读取那老是提示 内存溢出 下面是 实体类 Department 类 有setter 和getter 方法 private Integer id; private String name; private Set<Employee> employees=new HashSet<Employee>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } Emloyee 类 有setter 和getter 方法 private Integer id; private String name; private Department department; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } 下面是映射类 Department.hbm.xml <hibernate-mapping package="org.xxf.OneToManyA"> <class name="Department" table="department"> <id name="id"> <generator class="native"/> </id> <property name="name" type="string" column="name" /> <set name="employees"> <key column="departmentId"></key> <one-to-many class="Employee"/> </set> </class> </hibernate-mapping> Employee.hbm.xml <hibernate-mapping package="org.xxf.OneToManyA"> <class name="Employee" table="employee"> <id name="id"> <generator class="native" /> </id> <property name="name" type="string" column="name" /> <many-to-one name="department" class="Department" column="departmentId"></many-to-one> </class> </hibernate-mapping> 下面是测试类 private static SessionFactory sessionFactory; static{ sessionFactory=new Configuration()// .configure()// .buildSessionFactory(); } @Test public void testget() throws Exception{ Session session=sessionFactory.openSession(); session.beginTransaction(); Department department=(Department) session.get(Department.class, 1); System.out.println(department); System.out.println(department.getEmployees()); session.getTransaction().commit(); session.close(); } hibernate.cfg.xml <hibernate-configuration> <session-factory> <!-- 数据库基本配置信息 --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///htest</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- 数据库其他相关配置 --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="org/xxf/OneToManyA/Department.hbm.xml"/> <mapping resource="org/xxf/OneToManyA/Employee.hbm.xml"/> </session-factory> </hibernate-configuration> 测试后 它就老提示 我内存溢出 java.lang.StackOverflowError at java.lang.Integer.toString(Integer.java:305) at java.lang.Integer.toString(Integer.java:116) at java.lang.String.valueOf(String.java:2932) at java.lang.Integer.toString(Integer.java:682) at java.lang.String.valueOf(String.java:2827) at java.lang.StringBuilder.append(StringBuilder.java:115) at org.xxf.OneToManyA.Employee.toString(Employee.java:13) at java.lang.String.valueOf(String.java:2827) at java.lang.StringBuilder.append(StringBuilder.java:115) at java.util.AbstractCollection.toString(AbstractCollection.java:422) at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:327) 往下 就一直重复出现错误 别人用一样的代码 测试就没问题 我就老报错 求各位大神帮指导一下
用hibernate的uuid注解生成主键, save时提示id出错
使用hibernate uuid注解 自动生成id值,在students和courses多对多的级联保存时, id保存出错 报错代码如下 ``` log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into students (sname, id) values (?, ?) Hibernate: insert into courses (cname, id) values (?, ?) Hibernate: insert into courses (cname, id) values (?, ?) Hibernate: insert into students_courses (sid, cid) values (?, ?) Hibernate: insert into students_courses (sid, cid) values (?, ?) org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at com.caidi.Test.TestManyToManyEach.test01(TestManyToManyEach.java:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:69) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:292) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 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: java.sql.BatchUpdateException: Field 'id' doesn't have a default value at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1693) at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1108) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ... 31 more ``` 1. Students类 ``` package com.caidi.beans; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="students") public class Students { @Id @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy = "uuid.hex") @Column(name="id") private String id; @Column(name="sname") private String sname; @ManyToMany @Cascade(value={CascadeType.SAVE_UPDATE}) @JoinTable(name="students_courses",joinColumns={@JoinColumn(name="sid",referencedColumnName="id")},inverseJoinColumns={@JoinColumn(name="cid",referencedColumnName="id")}) private List<Courses> courses; public Students() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public List<Courses> getCourses() { return courses; } public void setCourses(List<Courses> courses) { this.courses = courses; } } ``` 2. Courses类 ``` package com.caidi.beans; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="courses") public class Courses { @Id @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy = "uuid.hex") @Column(name="id") private String id; @Column(name="cname") private String cname; @ManyToMany(mappedBy="courses")//ManyToMany默认lazy加载 @Cascade(value={CascadeType.SAVE_UPDATE}) private List<Students> students; public Courses() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public List<Students> getStudents() { return students; } public void setStudents(List<Students> students) { this.students = students; } } ``` 3. Students_Courses.java ``` package com.caidi.beans; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="students_courses") public class Students_Courses { private String id; @Column(name="sid") private String sid; @Column(name="cid") private String cid; public Students_Courses() { super(); } @Id @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy = "uuid.hex") @Column(name="id") public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } } ``` 4. 测试代码 ``` package com.caidi.Test; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.caidi.beans.Courses; import com.caidi.beans.Students; import com.caidi.utils.HibernateTools; public class TestManyToManyEach { @Test public void test01(){ Session session = HibernateTools.getSession(); //开启事物 Transaction tr = session.beginTransaction(); try{ Courses c1 = new Courses();Courses c2 = new Courses(); c1.setCname("数学课"); c2.setCname("语文课"); List list1 = new ArrayList(); list1.add(c1);list1.add(c2); Students s1 = new Students(); s1.setSname("小明"); s1.setCourses(list1); session.save(s1); tr.commit(); System.out.println("finsh"); }catch(Exception e){ tr.rollback(); e.printStackTrace(); }finally{ if(session.isOpen() ==true){ session.close(); } } } } ``` mysql数据库 ![课程表courses](https://img-ask.csdn.net/upload/201802/26/1519657880_228265.png) ![学生表students](https://img-ask.csdn.net/upload/201802/26/1519657916_358265.png) ![中间表students_courses](https://img-ask.csdn.net/upload/201802/26/1519657943_981379.png)
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# clr dll c# 如何orm c# 固定大小的字符数组 c#框架设计 c# 删除数据库 c# 中文文字 图片转 c# 成员属性 接口 c#如何将程序封装 16进制负数转换 c# c#练手项目
立即提问